0

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?

2 Answers 2

2

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>
    )
}
Sign up to request clarification or add additional context in comments.

1 Comment

its a different perspective, thanks for taking time and explaining @NGY
1

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.

2 Comments

if id is string/number , will includes still work ?
includes works with strings, so you can convert id to a string if it isn't already with String(id)

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.