mucle6
mucle6

Reputation: 655

How to bind a prop to a component in React

Given the following component

const A = ({prop1,prop2}) => (
    <div>{prop1 + ' ' + prop2}</div>
)

How can I bind / create a closure of / curry prop1? In other words what is the right way to write the following such that A gets {prop1:'prop1!',prop2:'prop2!'}

const B = ({BoundA}) => (
    <div><BoundA prop2 = 'prop2!' /></div>
)

<B A = {<A prop1 = 'prop1!' />} /> 

Upvotes: 2

Views: 7349

Answers (2)

acdcjunior
acdcjunior

Reputation: 135752

How about just picking up the props and passing down like:

<div><A prop1={BoundA.props.prop1} prop2='prop2!' /></div>

Example:

const B = ({ BoundA }) => (
  <div><A prop1={BoundA.props.prop1} prop2='prop2!' /></div>
)

<B BoundA={<A prop1='prop1!' />} />

And, if you want to reuse the <A /> instance passed in <B BoundA={<A, you can't. You won't be able to add props to existing elements.

If you did something like:

const B = ({ BoundA }) => {
  BoundA.props.prop2 = 'new prop prop2';
  return <div>{ BoundA }</div>
};

You'd get:

TypeError Cannot add property prop2, object is not extensible.

So, if you have several props, your alternative is to use React.cloneElement():

const B = ({ BoundA }) => (
  <div>{ React.cloneElement(BoundA, {prop2: 'prop2!' }) }</div>
)

<B BoundA={<A prop1='prop1!' />} />

Upvotes: 2

mucle6
mucle6

Reputation: 655

React components are Immutable so once a component is created the props can't be changed. To update props, we have to use React.cloneElement() like so

const B = ({ BoundA }) => (
 <div>React.cloneElement(BoundA,{prop2:'prop2!'})</div> 
)

This solution is similar to acdcjunior's but it doesn't require B to import A. This also makes it possible for B to generically accept components without accepting both the component and an instance of the component

Upvotes: 1

Related Questions