0.0.1 • Published 7 years ago

react-walk-element-tree v0.0.1

Weekly downloads
1
License
MIT
Repository
-
Last release
7 years ago

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,
)