DEV Community

Ray
Ray

Posted on

React: Template Literals & Ternaries Instead of if/else Statements

This week we continue our React study notes, and this week I've learned two simple but very useful uses: Template Literals & Ternaries Instead of if/else Statements.

Continue to use the book model used in the first two study notes. First, we create a simple summary, in defining an object we can use the Template Literals

`${js or element's own attributes}`
Enter fullscreen mode Exit fullscreen mode

JavaScript can be used inside to achieve the effect we wish to print! Eg:
Image description

For example, we want the printed String to determine whether the book object has the property 'hasMovieAdaptation', where we use the judgment

${hasMovieAdaptation ? "(if true)" : "(if false)"}
Enter fullscreen mode Exit fullscreen mode

See, the output changed
Image description

Now let's take this simple judgment and add a little bit of new conditions, such as for the number of pages to be judged.

pages > 1000 ? "over 1000": "less than 1000";
Enter fullscreen mode Exit fullscreen mode

But every time you need to print when writing such a long judgment is always inconvenient, then we try to define this judgment as an object, like this:

Image description

You can see that our log successfully prints out the result of the desired judgment.

Top comments (0)