2

i want to render a jsx if condition is true using ternary operator and using react and javascript.

what i am trying to do? when the variable admin is true an count is < 0 i donot want to display the button "add". and should display under conditions below

admin && count > 0
!admin 

below is my code,

render = () =>{
    return (
        <button> add </button> //should render this based on condition
    )
}

Could someone help me fix this. thanks.

EDIT: below are the conditions to be displayed

count > 0 && is_admin
count > 0 && !is_admin
count <0 && !is_admin

condition when not to be displayed

count <0 && is_admin
1
  • 1
    In addition to the other answers, you can also use a guard and return null if your condition fails. e.g. render() {if (!myCondition) return null; return <button>...</button>} Commented Jun 5, 2020 at 12:01

2 Answers 2

1

For this case, you can use short circuit evaluation:

render() {
    return (
      <>
        {((admin && count > 0) || !admin) && <button> add </button>}
      </>
    )
}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks but this will not display if it is not admin and count < 0
@someuser2491 Just double checked your question, and realised I missed out the other condition. I have just updated my answer.
0

You can simply add "&&" to render conditionally

render = () => {
    myCondition && (<button>test</button>)
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.