admin管理员组

文章数量:1327750

I can a react ponent which is based on the const.

const MyComp = (prop) => ... etc

In it I have some JSX:

<div id="myDiv">
        Stuff Here
</div>

I have a prop which is currently true called myprop.

So I want to add a condition the myDiv ... for example:

<div id="myDiv" {if myprop === true}>
        Stuff Here
</div>

So that the div will show only if the prop is true.

How do I do this in React?

I can a react ponent which is based on the const.

const MyComp = (prop) => ... etc

In it I have some JSX:

<div id="myDiv">
        Stuff Here
</div>

I have a prop which is currently true called myprop.

So I want to add a condition the myDiv ... for example:

<div id="myDiv" {if myprop === true}>
        Stuff Here
</div>

So that the div will show only if the prop is true.

How do I do this in React?

Share Improve this question edited Nov 8, 2018 at 20:35 Dacre Denny 30.4k5 gold badges51 silver badges66 bronze badges asked Sep 10, 2018 at 9:48 user10128152user10128152
Add a ment  | 

2 Answers 2

Reset to default 5

If I understand your question correctly, then this should be achievable with the following JSX syntax:

{ (myprop === true) && <div id="myDiv">
        Stuff Here
   </div>
}

To summarize what is happening, this is effectively an expression that says, "if myprop === true" then "render the div"

As @DacreDenny said but I can short it further like

{myprop && <div id="myDiv">Stuff Here</div>}

本文标签: javascriptReact inline if condition then display this divStack Overflow