Nathan_HyAn
Nathan_HyAn

Reputation: 23

Using an if statement to apply inline style (React)

I want to apply conditional rendering using inline styling with React.

The thing is: i have a prop that spits either 1, 2 or 3 depending on the scenario. So i want that when the output is 1 or 2, the div appears (display: 'block'), but when 3, sets to none.

<div style={{
            display: () => {
              if (this.props.info.realm === 1 || this.props.info.realm === 2) {
                console.log("this has to be block");
                return "block";
              } else {
                console.log("this has to be none");
                return "none";
              }
            }
          }}>

          <p>Hola</p>
</div>

When this code runs i get nothing but the sole Div. Not even the console.logs.

Upvotes: 2

Views: 2359

Answers (1)

Jee Mok
Jee Mok

Reputation: 6556

You need to call the function in order to get the value;

In your case, you can do IIFE (Immediately Invoked Function Expression):

      <div style={{
            display: (() => {
              if (this.props.info.realm === 1 || this.props.info.realm === 2) {
                console.log("this has to be block");
                return "block";
              } else {
                console.log("this has to be none");
                return "none";
              }
            })()
          }}>
          <p>Hola</p>
      </div>

Alternatively, you can do it outside of the render method

function getDisplay() {
  if (this.props.info.realm === 1 || this.props.info.realm === 2) {
    return "block";
  }
  else {
    return "none";
  }
}

return (
  <div style={{ display: getDisplay() }}>
    <p>Hola</p>
  </div>
);

or using a getter to make it cleaner if you're using a class component:

get display() {
  if (this.props.info.realm === 1 || this.props.info.realm === 2) {
    return "block";
  }
  else {
    return "none";
  }
}

render() {
  return (
    <div style={{ display: this.display }}>
      <p>Hola</p>
    </div>
  );
}

Upvotes: 2

Related Questions