React is the most popular library for building user interfaces right now, and for a good reason. It offers everything you need to build interactive, lightweight, and fast web applications. In this article, we’ll try to show you how to implement dynamic features in React. Namely – how to conditionally render and style elements and components.
Dynamic rendering in React
When building apps, sometimes you want to render certain parts of the page only if certain conditions are true. A simple example is to render a dashboard control panel only if the user is successfully logged in.
Using ternary operators is the most common way to implement dynamic rendering in React. It allows you to quickly check a condition and return a component if the condition is true, and another component if the condition is false. Alternatively, you can return nothing if the condition is false, or set up an additional condition, similar to else if statement in JavaScript.
You can also use familiar if/else and switch statements to conditionally return elements or components. However, these are not compatible with JSX. You will have to use these statements outside the JSX. In case of functional components, use else and switch in the function body. In class components, either in the body of the render() function or in the class definition.
If you have multiple and/or complex conditions for rendering a certain component, it’s best to skip ternary operators. They become less readable with complex conditions. Use familiar if/else statements. They work the exact same way in React.
For simple use-cases, you can use the logical AND operator (&&). You can use it to connect the condition and the component that needs to be rendered. Condition comes first, followed by AND operator, and followed by the component. If the condition is true, React will render the component. If not, nothing will be rendered. This approach is useful as it can be embedded inside JSX.
You can also use a library like react-router to dynamically render component for certain routes. The library also allows you to get current path and url in React.
Conditions for rendering
You can use any condition to dynamically render an element or a component. In practice, most React developers use values from state or props. These values are usually tied to event handlers, so user actions can determine when the component or element is rendered. For example, you can set up an onClick event handler to render (or not render) the element when the component clicks a button. The event handler updates the state variable, which in turn conditionally renders the component.
In functional components, usually we use the useState hook to create a variable and a function to update it. You will need that function to update the state from the event handler. In class components, you will need the setState() method to update the state. Keep in mind that React automatically re-renders the page every time there’s change to state or props. So updating the state will cause the condition to be evaluated again, and the page layout to be accordingly updated.
Dynamic Styling
The entire purpose of React is to build interactive websites. In other words, the application needs to respond to the user’s actions. Visual cues are often the strongest. If there’s been an error, make text red. This is only possible thanks to dynamic styling in React.
It’s important to remember that everything in React is actually JavaScript. Even the parts that look like HTML. JSX is just an easier way to structure web applications without having to work with top-level React API. JSX works similarly to HTML, except it also allows you to embed JavaScript expressions into the structure of your app. So you can set className attribute to a dynamic string or set inline styles to a JavaScript object where properties correspond to CSS properties. Here’s a guide that shows how to do string interpolation, which is very useful for dynamically styling elements in React.
Similar to conditional rendering, in this case we also use state values to set up conditions. In turn, state values are prone to change in response to users actions. We define and set up event handlers to change state values when users click or provide any other input. When state values change, the React component and all its children trigger a re-render to make sure the app depicts the latest changes on screen. In this re-render, React might realize that the condition for styling is now met, and apply the new conditional style.
Let’s look at an example:
<div style={{backgroundColor: dark ? “black” : “white”}}>contents of the page</div>
Let’s say there’s a checkbox that when checked, sets the dark state variable to true. Then checking and unchecking that checkbox (user action) determines the style of the page.
Notice that we need to use double curly braces to set inline styles in React. One pair of braces tells React to interpret the following part as a dynamic expression. The inner pair of curly braces are there to open and close the JavaScript object.
We could also conditionally set the className attribute. Note that React is entirely written in JavaScript, a language where class is a reserved word.
It’s not a requirement to use a ternary operator to conditionally style or render elements in React. However, it’s the easiest and most readable approach. Also, if and switch statements can not be embedded in JSX, so you will have to define these conditions outside the JSX and then reference variables inside JSX. For more complex or multiple conditions, this might be the better approach. But for the sake of simplicity, I almost always use ternary operators or logical AND (&&) operators to implement these dynamic features.
Summary
In today’s article, we discussed how to implement two important features in React. Hopefully you are now familiar with conditional rendering and styling, and why state values are necessary to implement these dynamic features.