TheLearner
TheLearner

Reputation: 2863

How to pass dynamic props to child component in ReactJS?

I am dynamically toggling between two components like so:

{this.props.firstname ? (

    <ProfileDropdown
        firstname = "SomeFirstName"
    />

) : (
     ....
)}

But instead of "SomeFirstName", I want to pass this.props.firstname as the value for the firstname prop to the <ProfileDropdown /> component. How do I do that?

Upvotes: 1

Views: 765

Answers (1)

Mayank Shukla
Mayank Shukla

Reputation: 104369

Basic Rule:

We can embed any JavaScript expression in JSX by wrapping it in curly braces.

To specify any expression inside JSX, we need to use {}, use it and put this.props.firstName inside that.

Write it like this:

<ProfileDropdown
     firstname = {this.props.firstname}
/>

Check the DOC: Embedding Expressions in JSX

Update:

Check this example, you will get a better idea:

{this.props.firstname ? (         //expression so {}
    <ProfileDropdown              //jsx
        firstname = {1 == 1 ?     //here {} to put expression inside JSX
            <div> {1+1} </div>    //inside div(JSX), so use {} again to put expression 1+1
            : <div>World</div>
        }
    />
)

Upvotes: 5

Related Questions