Search
Learn
Share

If / else statement inside of React Component's Render method

Published by Profile Image LGK on 4 August, 2017
36 views
Sometimes (well, actually pretty often) you have to use conditional statements inside of React Component's Render methods.

You could do it like this:

import React from "react";

class MyComponent extends React.Component {
render() {
return (
<div>
{"LGK" == "awesome" ?
<h1>LGK is awesome!</h1>
:
<h1>LGK is not awesome :C</h1>
}
</div>
);
}
}

This works without any problem. But you always have to set the else part. But in many situations you only need the "if part".
In this case, this way is much nicer:

import React from "react";

class MyComponent extends React.Component {
render() {
return (
<div>
{"LGK" == "awesome" &&
<h1>LGK is awesome!</h1>
}
</div>
);
}
}