0

I have a bunch of components that require the same prop, and going through them individually to add the JSX is cumbersome, can I create a piece of JSX in the parent that will be passed to these child components as a prop?

Here's basically what I want to do:

function App(props) {
    /*not part of the actual code, but I want to 
    pass this h1 tag into the  bottom components as a prop*/
    <h1>{props.heading}</h1> 
    <Home heading="Home"/>
    <AboutMe heading="About Me"/>
    <Contact heading="Contact"/>
}

I know the code above isn't how you're supposed to do it, but is there a way I can accomplish that functionality?

1
  • As in <Home heading={ () => <h1>{props.heading}</h1> }/> ? Commented Nov 21, 2018 at 1:50

1 Answer 1

1

Yes, that's possible. Just assign your JSX component to a variable and pass that variable as a prop. You have the right idea. For example:

var customHeader = <h1>Here's a custom component</h1>

You can also set customHeader to a React component such as: var customHeader = <CustomHeader />

You can pass through <MyComponent header={customHeader}/> and in your render function of MyComponent page, you can simply use {this.props.header} to load your component. This can be repeated for any number of components.

Edit based on comments. In that case, I would wrap the component in a function. For example:

getCustomHeader = (title) => {
    return <MyHeader
        headerTitle={title}
    />
}

Now, in your render function, you can call getCustomHeader.

render() {
    return <div>
        <MyComponent1 header={this.getCustomHeader("Title A")} />
        <MyComponent2 header={this.getCustomHeader("Title B")} />
    </div>
}
Sign up to request clarification or add additional context in comments.

5 Comments

Would I need to add {this.props.header} to every component I need this custom header for?
Yes. That's pretty much the case but you don't have to make a new variable for each new header (which would defeat the whole point as the edit that you commented). You can pass customHeader into more than 1 component. For example you can do <MyComponent header={customHeader} /> and <MyComponent2 header={customHeader} />.
What about if each header is different for each component. ComponentA's header should be "Title A", and ComponentB's header should be "Title B" and so forth?
Okay, wow, creating a function was so simple...not sure why I didn't think about it. Thanks I accepted your answer.
No problem, glad to help!

Your Answer

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