Home > Net >  React conditional rendering and return the value
React conditional rendering and return the value

Time:05-26

Need a little guidance with conditional rendering in react


class Car extends React.Component {
id = '123456'

  render() {

   if("id".includes("1") === true){

    return <h2>$$${id}</h2>;

}
else{
         return <h2>{id}</h2>;
  }
}

For rendering $$$ for certain condition , apart from using if else and rendering is there any way to conditionally render ??? a better way and the return can be quite long in big applications is there a way to write conditional and return the value according to it?

CodePudding user response:

There's a variety of ways to do conditional rendering. Here is one example with a ternary operator for simple cases:

    render() {
         return <h2>{id.includes("1") ? "$$$" : ""}{id}</h2>
    }

You can also look into using a switch statement, where you move the conditional logic outside of the render function.

CodePudding user response:

Your question is not very clear so do well to add some clarity if my answer is not satisfactory.

When you want to conditionally render in react you can use the short-circuiting property of the && operator.

For example:

(false && "Logged In")
//Logged In

So using this idea, you can do the same for components

function App(props) {
    let element
    if(props.loggedIn) {
        element = <div>Logged In</div>
    } else {
        element = <div>Not Logged In</div>
    }
    return element
}

simply becomes

function App(props) {
    return (
        <div>
            {
                props.loggedIn && 
                <h3>You're logged in as {props.data.username}</h3>
            }
        </div>
    )
}
  • Related