0

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?

2 Answers 2

2

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 ...

Sign up to request clarification or add additional context in comments.

3 Comments

The somecomponent cannot be used as such as its generic here, it is passed as expression component {SomeComponent}
@MithunShreevatsa fair enough, here is a quick example I've made, it shows a quick basic render prop, it is up to you how far you want to abstract it, you can also make a HOC wrapper codesandbox.io/s/smoosh-water-61jip?file=/src/App.js
Good effort and appreciate your time and knowledge, good going. Keep it up
0

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...'
    });
  });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.