React Tricks

2019-10-03 00:15:00 +0000 - Written by Carl Burks

Have you ever wanted to switch out a component based on a value? Did you write a switch statement or a ternary or some other nonesense? Wouldn’t it have been nicer to have a component that could just handle it for you?

What about mapping an array? Same thing right? You’d like a component to handle it for you. Here are a couple of sample components:

const Foo=(props)=><div style=>{props.test1} - {props.test2}</div>
const Bar=(props)=><div style=>{props.test1} - {props.test2}</div>

Those aren’t the Switch or the Mapper, they are just some simple components.

For your coding pleasure let’s start with the switch:

const Switch=(props)=>React.cloneElement(props.lookup[props.value],props);

First it is expecting a lookup dictionary which will have a key for each entry. Then it uses the props.value to pick the element, but what about that cloneElement? It is going to shove in the props into the component we just looked up. Lets look at it in action:

<Switch lookup=bob value="bob" test1="tester" test2="tester2" />

It turns around and renders this:

<Foo lookup=bob value="bob" test1="tester" test2="tester2" />

If you switch the value it renders this:

<Bar lookup=bob value="bill" test1="tester" test2="tester2" />

That is pretty powerful.

Well what about the map? Assume we still have those Foo Bar components.

const DatasourceMapper = (props)=>props.dataSource.map((item,i)=>React.cloneElement(props.children,item));

We are using the same trick as before with the cloneElement, but we are looping from the dataSource, but instead of passing the parent props we are passing the item from the map to the child.

Let’s take a look at using it:

<DatasourceMapper dataSource={[{test1:"bob",test2:"jones"},{test1:"bill",test2:"bob2"}]}><Foo/></DatasourceMapper>

This makes for some generic reusable components, which act as control of flow operators.