How to redirect to another page in React

React is a very popular tool for building web applications, but it alone isn’t enough to build a fully-fledged web app. It’s only a UI library for building interfaces, but you also need additional tools for essential features like routing. For that, React developers often use react-router library that provides all essential features.

What is react-router

As is typical for React library, react-router provides custom components you can incorporate into your app to do what you need. For example, you use <Route> components to specify the route that displays specific set of components. <Link> components, when clicked, take users to a specified URL. They work like a normal anchor tag in HTML, except they don’t reload the page. <Link> components are optimized for single page applications. As you know, in SPAs, everything is loaded on one page, hence their name Single Page Applications. However, moving through different URLs displays different components and hides others. This creates the illusion of normal browsing experience, where you go from one page to another to see what you need.

Redirect in React

Now, let’s talk about the main topic. There are a number of ways to redirect in React. Some are declarative, some programmatic. A blog post on SimpleFrontEnd explores this topic very well, but I’ll try to add my 2 cents.

A declarative way to redirect in React involves using the <Navigate> component. Sixth version of react-router provides this component. If your application renders a Navigate component, users will be redirected to the URL specified in the to attribute.

Naturally, you don’t want users to always be redirected to another page. So you can use curly braces inside JSX to conditionally render <Navigate> component. You set up a condition, and render <Navigate> only when it is met. Here’s a guide where they explore this approach. The condition can be based on a state value (tied to the user’s inputs) or any JavaScript expression.

This is great, but some React developers consider this approach to be difficult to follow. Instead, you can do the same by simply using normal functions in JavaScript.

The latest version of react-router library also provides useNavigate hook. It returns an instance of a function you can use to redirect users to a specified URL. First, you create a variable and set it to a navigate function. Afterward, you can call this variable with a string argument that specifies the URL path for redirection.

Let’s look at an example:

const redirect = useNavigate()
<onClick={() => redirect(‘/homepage’}>Click to redirect</button>

As you can see, this is a much better way to redirect users after clicking a button. A normal <Navigate> component would require a number of additional steps. For example, a state variable that holds a Boolean value, which determines whether user should be redirected or not.

You can now use redirect() function to redirect users whenever it’s called. In the example, you simply call a function whenever a click event happens. It’s also more readable than having a custom <Navigate> component with a conditional rendering expression embedded in JSX. You can use this function in other event handlers like onSubmit, to redirect user once they submit the form.

Expand / Collapse feature in React

When browsing any web application to consume content, it’s impossible to show users important information about every piece of content. But you don’t need to show the entire content. For instance, Netflix doesn’t show full information about every movie. It shows the category, director, length, and other important details. Users need to open the movie to actually watch it.

That’s the idea behind expand/collapse feature, which you can use to improve the UX of React apps. Without further ado, let’s talk about the basic steps to implement it in React.

How to expand and collapse in React

First, you need some way to toggle the current status of the content. This is usually a state variable with a Boolean value. If it’s false, then the content is collapsed. If it’s true, then the content is expanded. In most web applications, you have a button used to toggle content status. Or sometimes clicking the piece of content itself expands it. Buttons usually have an onClick event handler to toggle the state every time user clicks a button. Thus clicking a button one time might expand the content, and clicking it again will collapse it. This is how this feature is supposed to work.

Most often, you have a container with some parts that are conditionally expanded or hidden. To do this, you need one main container <div> that has content and another <div> container inside. Then you conditionally style the inner container to hide or show itself depending on the state variable. In the condition, you check the state variable. If and use inline styles display (or similar) to accomplish the desired result. Don’t forget that you need curly braces to embed JavaScript inside JSX.

Expand/collapse text

You can use similar principles (toggle state variable, event handlers) to expand and collapse div, list, and text. In the case of lists, you might need to slightly customize the map() method often used to render multiple elements and components based on arrays in React. As you know, map() accepts the index argument. If you want to render only the first 3 items of the list when the list is collapsed, you can add an if condition inside the map(). This way, map() will render only a few list items if the list is collapsed, and render all of them when the list is expanded.

You need to use a slightly different approach to expand and collapse a paragraph’s text. Instead of using map() and its index argument, you will use the slice() method to return only a certain number of characters from a string. More specifically, you need a ternary operator that checks the current value of the toggle state variable. If it’s true, then the text needs to be expanded, and the ternary operator should return the full text. If it’s false, then it needs to return the first 20 or 30 characters of the string.

Hopefully, this was a good overview of how to implement expand/collapse feature in React. If you need advanced features like specifying animation and its speed, then using libraries like react-collapsed is a good idea. SimpleFrontEnd has a tutorial with many examples of how to implement expand/collapse in React.

Conditional classNames in React

In this article, I want to talk about conditional styling in React. Specifically, about setting multiple className values conditionally. A lot of beginner React developers get confused about conditional classnames, especially if there are multiple values involved.

Setting className in JSX

First, let’s clarify an important detail – in React, we set classes to elements using className attribute. This is necessary because JSX ultimately compiles to JavaScript, and class is a reserved word, not to be confused with JavaScript’s class syntax.

Otherwise, the syntax of setting className to a React element looks pretty similar to HTML. Value looks like a string. To set multiple values, you simply separate them by a space.

Conditional className in JSX

So let’s explore how to set multiple classes conditionally in React. Obviously, you are going to need JavaScript to dynamically set the value of className attribute. With JSX, you need to use curly braces ( {} ) to embed JavaScript expressions.

Now, let’s talk about state. Most of the time, we implement conditional classes to respond to changes in the state. For example, user toggles the ‘Dark Mode’ switch. If you know controlled components, you should know that typically input elements are tied to state values in React. So changes in input triggers changes in the state.

So when you define multiple conditional className values, you need to look at state value. Depending on the current value of the state variable, you should determine the class. You can do that in multiple ways. The easiest is to use a ternary operator, which works like this: first, we write a condition, followed by a question mark. Then we the value to be returned if the condition is true. Then follow it up by a semicolon and write an alternative value, if the condition is false. Once you get used to it, ternary operators are really easy to write.

Ternary operators are fine if you have only one className value. To set multiple values, template literals might be better. These are just like normal strings, but they allow you to embed JavaScript expressions.

Use a backtick to mark the beginning and end of template literals. Then use a dollar sign ($) to embed JavaScript inside template literals.

You can also write a function that takes a state variable as an argument and returns a certain combination of className values. Then set className attribute to the result of that function.

classnames() function for handling multiple conditional className values

Finally, there are also various external utilities and libraries for setting conditional className values in React. The classnames utility is the best one I know. You can use it for advanced use cases. For example, when you want two values to be always applied, and three conditional values. You can do that with the classnames() function.

SimpleFrontEnd has excellent guide on setting multiple className values conditionally in React.

General classes or specific classes?

Experienced developers define many classes, and apply combinations of these classes to great effect. This gives us more flexibility to style elements without writing too much and complicated classes. Similarly, you should aim to define as few classes as possible, and reuse them to achieve the desired goal.