Skip to content

How to Use Ternary Operator in React JS?

Last updated on July 10, 2023

In ReactJS, you can use the ternary operator as a conditional operator to conditionally render content or apply styles to elements. The ternary operator has the following syntax:

condition ? expression1 : expression2

Here’s an example of how you can use the ternary operator in ReactJS:

import React from 'react';

function MyComponent() {
  const isLoggedIn = true;

  return (
    <div>
      {isLoggedIn ? <p>Welcome, User!</p> : <p>Please log in.</p>}
    </div>
  );
}

export default MyComponent;

In the example above, the isLoggedIn variable is set to true. If it’s true, the ternary operator evaluates the first expression (<p>Welcome, User!</p>) and renders it. If isLoggedIn is false, the second expression (<p>Please log in.</p>) is evaluated and rendered instead.

You can use the ternary operator for more complex logic as well. Here’s an example where the style of a component is conditionally applied based on a variable:

import React from 'react';

function MyComponent() {
  const isHighlighted = true;

  return (
    <div>
      <h1 style={{ color: isHighlighted ? 'red' : 'black' }}>Hello, React!</h1>
    </div>
  );
}

export default MyComponent;

In this example, if the isHighlighted variable is true, the text color of the <h1> element is set to 'red'; otherwise, it’s set to 'black'.

Remember that the ternary operator can be used within JSX expressions to conditionally render components, apply styles, or even set dynamic values for attributes.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments