قالب وردپرس درنا توس
Home / Tips and Tricks / Conditional display in React – CloudSavvy IT

Conditional display in React – CloudSavvy IT



Reply logo on a dark background

React’s declarative rendering approach allows you to quickly write rich components that combine layout, presentation, and logic. However, it can make it more complicated to show UI sections conditionally. Here are a few methods you can use to list components on demand.

Understanding the problem

Traditional templates make it easy to implement conditional display. Here̵

7;s how you could do that in Handlebars, a JavaScript template engine:

{{#if user}}

You are logged in!

{{else}} Login
{{/if}}

When you work in React, you generally write JSX. Although JSX looks like like HTML, it is converted to regular JavaScript by the React build process. It ends as a series React.createElement() calls.

That means you cannot use unaltered JavaScript conditions within JSX. If you try to do something like this, you will get a compilation error:

const MyComponent = props => {
    return (
        <div>
            if (props.user) {
                <p>You are logged in!p>
            }
            else <a href="/login">Logina>
        div>
    );
};

If statements in JSX require a little more attention. There are several approaches you can choose from. The option you choose depends on the complexity of the condition, or one else branch, and whether it affects the readability of your code.

Cancel from JSX

The easiest way to fix the above code is to use the if from the return pronunciation:

const MyComponent = props => {
    if (props.user) {
        return <p>You are logged in!p>;
    }
    else {
        return <a href="/login">Logina>;
    }
};

The condition has been removed from the JSX. Instead, it uses two independent JSX nodes, the return of which is determined by one if statement in the body of the function. This approach is clearly understandable and keeps the two branches completely separate.

Using conditional expressions

The above solution usually only works in the simplest components. You tend to duplicate code, such as at the top level

present in both JSX nodes in the example.

Usually you need something more elegant. JSX supports JavaScript expressions enclosed in curly brackets ({}You can use Boolean equations and the ternary operator to obtain inline conditional representation.

const MyComponent = props => {
    return (
        <div>
            {props.user ? <p>You are logged in!p> : <a href="/login">Logina>}
        div>
    );
};

This example works as intended without any duplication of code. When the user is verified, the logged in text is displayed. When the user is logged out, the expression evaluates to false so that the login link appears.

Inline expressions are the most commonly used JSX conditional rendering technique. However, they can be cognitively demanding, especially if the true and false return values ​​are themselves expressions. When an expression becomes impractical, you can span it over several lines. This can improve readability and ensure that your file stays within the line length limits imposed by your linter.

Scenarios where there is no ‘other’

Now let’s modify the above example by removing the text “you are logged in”. Our product manager has decided it is not necessary in this section of the app. The holder

should now be empty when the user is logged in.

React makes you return null to indicate that there is nothing to render. Adjust the conditional expression of the component accordingly.

const MyComponent = props => {
    return (
        <div>
            {props.user ? null : <a href="/login">Logina>}
        div>
    );
};

React also supports false with the same meaning as nullThis means you can shorten the above by using JavaScripts && (and) operator to perform a boolean comparison.

const MyComponent = props => {
    return (
        <div>
            {!props.user && <a href="/login">Logina>}
        div>
    );
};

The left side of the expression evaluates to false when the user is logged in. Because the two parties are connected with one and, the overall expression also evaluates to falseAs a result, nothing is displayed when the user is logged in.

When you are logged out, the left side evaluates to trueThe right side will always be truthful as it will be converted to a JavaScript object when the JSX is transported. This form of evaluation returns the right side of the expression so that the login link is displayed.

JavaScript evaluations are ‘shorted’. This means that the JSX on the right will not be unnecessarily constructed if the expression on the left returns false

Conditional Prop values

You can make props’ values ​​conditional using embedded expressions in the same style as shown above. Use a conditional or a ternary evaluation to determine the value to be delivered. Return a value of undefined is equivalent to not specifying the plug.

const MyComponent = props => {
    return (
        <div>
            <a href={(props.user.loggedIn === true) ? "/dashboard" : "/home"}>
                Home
            a>
        div>
    );
};

In this example, the destination of the “Home” link is dynamically adjusted depending on whether the user is logged in. Remember that a component’s props in JSX are transported to a regular JavaScript object, which is why this technique works. You really write the following:

React.createElement("a", {
    href: (props.user.loggedIn === true) ? "/dashboard" : "/home"
});

JSX is just a JavaScript syntax extension that allows you to declare React components in a form reminiscent of HTML.

Conditionals using logic components

Another way to achieve conditional representation is to include so-called “logic” components in your project. These are simple components that their children only return when a condition is met.

const IfComponent = props => {
    if (props.condition) return props.children;
    else return null;
}
 
const MyComponent = props => (
    <IfComponent condition={props.user.isLoggedIn}>
        <a href="/logout">Logouta>
    IfComponent>
);

This pattern can be the code in your render() function more intuitive. However, there is one big problem: the a element is always displayed, even if the if condition is not met. You can fix this by adapting IfComponent so that it calls a function instead of rendering children straight away.

const IfComponent = props => {
    if (props.condition) return props.renderChildren();
    else return null;
}
 
const renderContent = () => <a href="/logout">Logouta>;
 
const MyComponent = props => (
    <IfComponent
        condition={props.user.isLoggedIn}
        renderContent={renderContent} />
);

Now the a element is not constructed until the condition is actually met. This reduces unnecessary renders, which will improve performance when using complex components.

A variation on this pattern is to create a higher order component (HOC). Enables you to wrap a component with conditional functionality.

const ifHoc = (condition, component) => {
    return props => {
        if (condition()) return component(props);
        else return null;
    };
}
 
const LogoutLink = () => <a href="/logout">Logouta>;
 
const LogoutLinkOnlyWhenLoggedIn = ifHoc(props => props.loggedIn, LoginLink);
-
const ComponentUsingLoginLink = props => (
    <LogoutLinkOnlyWhenLoggedIn loggedIn={props.user.isLoggedIn} />
);

This approach can be a bit more difficult to understand at first. It is best if you want to keep the component to be displayed completely separate from the conditional logic. It also allows for reuse of complex logic, as any part can be wrapped ifHoc()The HOC wraps the original component and displays it only when the passed conditional function returns true

Performance issues

A few general performance considerations apply to all conditional rendering in React. The important thing is to minimize re-rendering as much as possible. Don’t try to replace huge bits of user interface in presentation components. Reproducing too much can quickly create a ‘feel slow’ feeling.

Also keep in mind that your conditional expressions are usually evaluated each time your component is displayed. If the conditions themselves are complex (such as assigning a series of objects to new objects) this too can cause a slowdown, especially on low-end hardware.

Conclusion

React requires you to take a slightly different approach to conditional rendering than traditional templates. This is because only JSX looks like such as HTML. It is returned to JavaScript objects, which are then used with React funcion calls.

Nevertheless, you have a variety of options when you need to conditionally render a component. The simplest option is usually to write conditional expressions in your JSX, either with && or the ternary syntax. You can fall back on a real if at the base of your render() method, or use a higher order component if JSX expressions would make your rendering stream more difficult to understand.


Source link

Home / Tips and Tricks / Conditional display in React – CloudSavvy IT

Conditional display in React – CloudSavvy IT



Reply logo on a dark background

React’s declarative rendering approach allows you to quickly write rich components that combine layout, presentation, and logic. However, it can make it more complicated to show UI sections conditionally. Here are a few methods you can use to list components on demand.

Understanding the problem

Traditional templates make it easy to implement conditional display. Here̵

7;s how you could do that in Handlebars, a JavaScript template engine:

{{#if user}}

You are logged in!

{{else}} Login
{{/if}}

When you work in React, you generally write JSX. Although JSX looks like like HTML, it is converted to regular JavaScript by the React build process. It ends as a series React.createElement() calls.

That means you cannot use unaltered JavaScript conditions within JSX. If you try to do something like this, you will get a compilation error:

const MyComponent = props => {
    return (
        <div>
            if (props.user) {
                <p>You are logged in!p>
            }
            else <a href="/login">Logina>
        div>
    );
};

If statements in JSX require a little more attention. There are several approaches you can choose from. The option you choose depends on the complexity of the condition, or one else branch, and whether it affects the readability of your code.

Cancel from JSX

The easiest way to fix the above code is to use the if from the return pronunciation:

const MyComponent = props => {
    if (props.user) {
        return <p>You are logged in!p>;
    }
    else {
        return <a href="/login">Logina>;
    }
};

The condition has been removed from the JSX. Instead, it uses two independent JSX nodes, the return of which is determined by one if statement in the body of the function. This approach is clearly understandable and keeps the two branches completely separate.

Using conditional expressions

The above solution usually only works in the simplest components. You tend to duplicate code, such as at the top level

present in both JSX nodes in the example.

Usually you need something more elegant. JSX supports JavaScript expressions enclosed in curly brackets ({}You can use Boolean equations and the ternary operator to obtain inline conditional representation.

const MyComponent = props => {
    return (
        <div>
            {props.user ? <p>You are logged in!p> : <a href="/login">Logina>}
        div>
    );
};

This example works as intended without any duplication of code. When the user is verified, the logged in text is displayed. When the user is logged out, the expression evaluates to false so that the login link appears.

Inline expressions are the most commonly used JSX conditional rendering technique. However, they can be cognitively demanding, especially if the true and false return values ​​are themselves expressions. When an expression becomes impractical, you can span it over several lines. This can improve readability and ensure that your file stays within the line length limits imposed by your linter.

Scenarios where there is no ‘other’

Now let’s modify the above example by removing the text “you are logged in”. Our product manager has decided it is not necessary in this section of the app. The holder

should now be empty when the user is logged in.

React makes you return null to indicate that there is nothing to render. Adjust the conditional expression of the component accordingly.

const MyComponent = props => {
    return (
        <div>
            {props.user ? null : <a href="/login">Logina>}
        div>
    );
};

React also supports false with the same meaning as nullThis means you can shorten the above by using JavaScripts && (and) operator to perform a boolean comparison.

const MyComponent = props => {
    return (
        <div>
            {!props.user && <a href="/login">Logina>}
        div>
    );
};

The left side of the expression evaluates to false when the user is logged in. Because the two parties are connected with one and, the overall expression also evaluates to falseAs a result, nothing is displayed when the user is logged in.

When you are logged out, the left side evaluates to trueThe right side will always be truthful as it will be converted to a JavaScript object when the JSX is transported. This form of evaluation returns the right side of the expression so that the login link is displayed.

JavaScript evaluations are ‘shorted’. This means that the JSX on the right will not be unnecessarily constructed if the left expression evaluates to false

Conditional Prop values

You can make props’ values ​​conditional using embedded expressions in the same style as shown above. Use a conditional or a ternary evaluation to determine the value to be delivered. Return a value of undefined is equivalent to not specifying the plug.

const MyComponent = props => {
    return (
        <div>
            <a href={(props.user.loggedIn === true) ? "/dashboard" : "/home"}>
                Home
            a>
        div>
    );
};

In this example, the destination of the “Home” link is dynamically adjusted depending on whether the user is logged in. Remember that a component’s props in JSX are transported to a regular JavaScript object, which is why this technique works. You really write the following:

React.createElement("a", {
    href: (props.user.loggedIn === true) ? "/dashboard" : "/home"
});

JSX is just a JavaScript syntax extension that allows you to declare React components in a form reminiscent of HTML.

Conditionals using logic components

Another way to achieve conditional representation is to include so-called “logic” components in your project. These are simple components that their children only return when a condition is met.

const IfComponent = props => {
    if (props.condition) return props.children;
    else return null;
}
 
const MyComponent = props => (
    <IfComponent condition={props.user.isLoggedIn}>
        <a href="/logout">Logouta>
    IfComponent>
);

This pattern can be the code in your render() function more intuitive. However, there is one big problem: the a element is always displayed, even if the if condition is not met. You can fix this by adapting IfComponent so that it calls a function instead of rendering children straight away.

const IfComponent = props => {
    if (props.condition) return props.renderChildren();
    else return null;
}
 
const renderContent = () => <a href="/logout">Logouta>;
 
const MyComponent = props => (
    <IfComponent
        condition={props.user.isLoggedIn}
        renderContent={renderContent} />
);

Now the a element is not constructed until the condition is actually met. This reduces unnecessary renders, which will improve performance when using complex components.

A variation on this pattern is to create a higher order component (HOC). Enables you to wrap a component with conditional functionality.

const ifHoc = (condition, component) => {
    return props => {
        if (condition()) return component(props);
        else return null;
    };
}
 
const LogoutLink = () => <a href="/logout">Logouta>;
 
const LogoutLinkOnlyWhenLoggedIn = ifHoc(props => props.loggedIn, LoginLink);
-
const ComponentUsingLoginLink = props => (
    <LogoutLinkOnlyWhenLoggedIn loggedIn={props.user.isLoggedIn} />
);

This approach can be a bit more difficult to understand at first. It is best if you want to keep the component to be displayed completely separate from the conditional logic. It also allows for reuse of complex logic, as any part can be wrapped ifHoc()The HOC wraps the original component and displays it only when the passed conditional function returns true

Performance issues

A few general performance considerations apply to all conditional rendering in React. The important thing is to minimize re-rendering as much as possible. Don’t try to replace huge bits of user interface in presentation components. Reproducing too much can quickly create a ‘feel slow’ feeling.

Also keep in mind that your conditional expressions are usually evaluated each time your component is displayed. If the conditions themselves are complex (such as assigning a series of objects to new objects) this too can cause a slowdown, especially on low-end hardware.

Conclusion

React requires you to take a slightly different approach to conditional rendering than traditional templates. This is because only JSX looks like such as HTML. It is returned to JavaScript objects, which are then used with React funcion calls.

Nevertheless, you have a variety of options when you need to conditionally render a component. The simplest option is usually to write conditional expressions in your JSX, either with && or the ternary syntax. You can fall back on a real if at the base of your render() method, or use a higher order component if JSX expressions would make your rendering stream more difficult to understand.


Source link