TheLearner TheLearner -3 years ago 150
React JSX Question

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?

Answer Source

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>
        }
    />
)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download