I am fairly new to react and this is a problem I am trying to solve.
There is a parent component parent which passes props to the child. One of these props, include an element to be rendered like this:
<child componentToBeRendered = {component} />
In the child, I want to take this component and pass a prop to it, which is defined in the child itself.
function child(props){ function toBePassed(){ ... } <props.componentToBeRendered fun = {toBePassed} /> }
I know that the above code is wrong and we cannot use <props.componentToBeRendered>
. So how can I pass a custom prop to this component?
The only way I can think of rendering the component is like: {props.componentToBeRendered};
How do I render this component with a custom prop defined in the child?
Advertisement
Answer
You can rename the passed component prop, render it as per usual, and pass props to it as per usual. Similar to Choosing the Type as Runtime
function Child(props){ const ComponentToBeRendered = props.componentToBeRendered; function toBePassed(){ ... } return <ComponentToBeRendered fun={toBePassed} />; }
I’ve usually used this pattern with prop destructuring in the function signature, renaming the destructured prop.
function Child({ componentToBeRendered: ComponentToBeRendered }) { function toBePassed(){ ... } return <ComponentToBeRendered fun={toBePassed} />; }