user7217977
user7217977

Reputation:

ReactJS, passing prop from parent to child component?

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?

Upvotes: 0

Views: 558

Answers (1)

Kevin Bai
Kevin Bai

Reputation: 631

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

Upvotes: 1

Related Questions