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

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 (
            <di>
                {"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>
        );
    }
}

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.