Reputation: 3599
I have a requirement to construct props dynamically, confused a bit to structure this. See the following example, the children expression component requires parent component title in this case.
function SomeComponent(props){
return <h1>{props.title}</h1>
}
import SomeComponent from 'someForm';
const contents = {
title: 'hello',
form: SomeComponent
}
Another component:
<Another data={contents}>
function Another(props){
return (
<Form title={props.data.title}>
{props.data.form} => title should be passed to this component expression
something like: <props.data.form title={props.data.title}>
Is it possible or how to do this?
</Form>
);
}
What's the best way to achieve this? HOC is a option, but how exactly is the question?
Upvotes: 0
Views: 138
Reputation: 3599
I was able to manage it like below for my requirement by dynamically constructing props without the need of HOC and this suits to my requirement but i am not sure about the performance.
const componentWithExtraProp = React.Children.map(form, (child) => {
return React.cloneElement(child, {
title: 'Testing...'
});
});
Upvotes: 0
Reputation: 36
I hope I understood this correctly and I think render props pattern would be your best bet. https://reactjs.org/docs/render-props.html
essentially within your <Form />
component render children
and pass the variable down to the children as such
e.g
render = () => this.props.children(this.props.title)
assuming you have the props available inside <Form />
then you choose which component to render inside <Form />
as a child and with what props
<Form>
{(title) => <SomeComponent title={title}/>}
</Form>
title
just for this example as you're passing down title props.. in the future it can be called anything and refers to whatever you pass down to children, it can be props, state, specific handlers etc ...
Upvotes: 2