react-walk-element-tree
TypeScript icon, indicating that this package has built-in type declarations

0.0.1 • Public • Published

react-walk-element-tree

Usage

import {isValidElement, cloneElement} from 'react';
import walk from 'react-walk-element-tree';
function Thing ({color}) {return <span style={{color}}>Thing</span>} 
const orgEl = <div title='org-title'>cool<section><Thing/></section>cool</div>;

const transformedEl = walk(n => {
	// case react element
	if(isValidElement(n)) {
		// case for tag named Thing
		if (n.type.name === 'Thing') return cloneElement(n, {color: 'red'});
		// case for simple Tag
		if (n.type === 'div') return cloneElement(n.type, n.props);
	}
	// case for string node
	if (typeof n === 'string') return n.toUpperCase();
	return n;
})($el);
// becomes
<h1
  title="org-title"
>
  COOL
  <section>
    <Thing
      color="red"
    />
  </section>
  COOL
</h1>

Api

/**
 * Traverse A React Element Tree and transform node if neccessary
 * @param {(node: ReactChild) => ReactChild} transformer
 * @param {(node) => boolean} [skipIfSatisfy = () => false]
 * @returns {(node: any)=>(any|DOMElement<{children: (any|any|any)}, T>|any)}
 * @constructor
 */
function WalkReactElementTree (
  transformer: (node: ReactChild) => ReactChild,
  skipIfSatisfy: (node: ReactChild) => boolean = alwaysFalse,
)

Readme

Keywords

Package Sidebar

Install

npm i react-walk-element-tree

Weekly Downloads

0

Version

0.0.1

License

MIT

Last publish

Collaborators

  • sliv