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.

User-friendly features you can implement with React

Every business needs to have an internet presence. These days there are millions of websites and web applications competing for users’ attention. For this reason, web application needs to be easy to use and user-friendly. Otherwise, users will go to competitors’ websites and businesses lose out on a valuable customer.

Certain web application features are especially popular among businesses. For example, lazy loading is a prime example of a great feature that businesses want. It increases user retention and improves the experience for users with slow internet speed. This is just one example of a great UI feature that can be implemented with JavaScript. In this article, we’ll talk about more features.

Without further ado, let’s get started.


If a web application requires a lot of typing, autocomplete can be very useful. Users don’t like to type and autocomplete minimizes the amount of characters users have to enter. It can also be used to collect user inputs more accurately. When users type themselves, they might make a mistake or their input might have a typo. Autocomplete eliminates some of that risk.

You can implement the autocomplete feature with plain JavaScript, but many web developers like to use frameworks like Angular, Vue, and React. The latter has a number of packages and utilities that allow you to easily implement autocomplete feature in React.

Smart forms

This is another excellent feature that makes it easy to collect user inputs. Smart forms are a general label for user-friendly forms and their features.

Form validation is perhaps the most important feature of smart forms. It verifies submitted data and ensures its validity, so you know that collected data is verified. For example, form validation would check if the value entered into ‘Email’ field contains @. If it doesn’t, then the user has not entered a real email, and the form will highlight the error.

Another excellent feature is to empty the form after submit in React. If you want users to submit a form multiple times, it’s a very good idea to implement the ‘reset after submit’ functionality. Users don’t like to delete their previous inputs, it’s a hassle. As a web developer, you should delete it for them.

SimpleFrontEnd has published an excellent guide on how to do this in React. I’m sure there are other guides on how to do this with Vue, Angular, and other JavaScript-based frameworks.

Dark / Light mode

It has been proven that dark mode is easier on the eyes. Especially if someone has to look at your website for hours on end. It makes perfect sense to give them the option of using dark mode.

I know for a fact that dark mode is easy to implement with React. It shouldn’t be difficult with other frameworks and tech stacks either.

Expand / Collapse feature

Modern web applications have too much information in them. Developers can implement expand / collapse feature to allow users to see what they want to see, and ignore the rest. Users will greatly appreciate this and keep coming back to use your web application.

Infinite scrolling

Users often have to browse multiple pages of products, blog posts, or any other list. Infinite scrolling is the alternative to pages. Instead of having to go from one page to another, new contents are automatically loaded as soon as the user reaches the bottom of the page. This is an excellent feature, especially for e-commerce stores.

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.

Best practices for web development projects

Web development projects vary in complexity and length. Companies often

hire professionals to manage the development process.

In this blog post, we will go over web development best practices.

Start web development projects with
a plan

Define the Project Scope

For starters, clearly lay out what the web application will be about.
What purpose is it supposed to serve? What goals need to be met? Different
projects may be focused on selling, providing information, or social exchange.
For this reason, before you do anything else, you need to clearly define web
app’s purpose.

Gather Information:

Start by researching the competition. What features do they have and what
do their web apps lack? Is there something users complain about? This will help
you better understand the competitive market as well. More importantly, it’ll
help you create a website that looks better than anything else.

Create a Sitemap:

Once you have the general idea of a web application, create a list of all
pages in the web application. This way, it will be easier to create a
navigation system as well.

Design Wireframes

Wireframes help you visualize what the web app is going to look like.
Think of wireframes as sketches for animated films. These can be helpful to
understand your website and its features.

Choose Technology Stack

Next step is to decide what technology you’ll use to accomplish the goal.
Consider requirements of the project to make your decision. Make decisions on
programming language, framework, and other tech stacks you’re going to use.

Develop a Timeline:

Come up with a list of web development tasks that will need to be
completed. Then work with senior developers to estimate how long each task will
take. In web development, something always goes wrong. Adjust your plans

Plan Content

Web application is nothing without some content. Once you make important
decisions about the web app, create plans for pieces of contents to fill pages.
Make sure your content fits on each page. It should be compatible with web

Design and Development

Finalize the design. Coming up with a design is more complicated than
simple drawings. You need to come up with your brand visuals to ensure
consistency. Once you have the design, you can start the web development
process – creating actual web pages users can interact with.


Testing is a key part of building a reliable web application. Otherwise
code and overall application is going to be too unpredictable. Testing involves
unit testing, finding and fixing broken links, looking at browser and device
compatibility, and so on.

Launch and Maintenance

Once everything is working perfectly, it’s time to launch the website.
But the work doesn’t stop here. Regular maintenance, such as updating content
and fixing bugs, is necessary to keep the website relevant and functioning.

Prioritize Accessibility

Modern web applications should be built for everyone – including users
with disabilities. When building applications, you need to enable interactions
using non-traditional inputs. This is not a nice-to-have, but an essential
component of modern web applications. Here’s how to optimize apps for
accessibility in React.

First of all, use appropriate HTML elements when possible. This way,
assistive technologies can effectively decipher elements and content of your
page and help disabled users make use of it. For instance, use <button>
to perform button functionalities – respond to clicks, etc. You can use a
button and onClick event handler to specify scroll position of the view.
more here
. Do not use a simple <div> or even <span> to
accomplish the same.

Focus is an important part of interacting with a website. Good web
application needs to manage focus. Respond when elements get into focus, and
when they are no longer in focus.

Also, use the <label> element to properly assign labels to
every input element. This allows screen readers to help disabled users use
forms. These elements in React are almost the same as in HTML. Except in React,
we use the
instead of normal for attribute

Finally, choose color palette that works for color-blind people and
people who do not see well. It can be something simple like using green buttons
for ‘positive’ and red for ‘negative’. But there are many other ways to use
colors for communication.

Focus on UX

React is very popular because it makes room for modular design and
efficient development process. This approach helps designers and developers
collaborate and produce best results for building UIs.

Virtual DOM is React’s way of improving performance and speed. As a
result, React apps naturally offer smooth, responsive, and overall
user-friendly experience. React apps load immediately, users do not experience
delays when using the app.

Event handlers are key for ensuring smooth user experience. For example, you can use the onSubmit to clear
input fields after form is submitted.

Separation of Concerns

At first glance, it might seem like HTML, CSS, and JavaScript are not
separated in React. Template language JSX allows for integration of HTML and
logic. In reality, JSX is just JavaScript. React separates logic and display
differently than you might expect.

React is based on the idea of reusable components and how to use them to
build the architecture. Every component contains separate sections for logic,
design, and markup. Still, JSX allows you to embed JavaScript expressions into
what looks like HTML markup.

Angular and Vue.js approach this differently. Logic and design are
separated into different files, or different sections of the same file.

Here’s how to achieve separation of concerns to achieve simple and
straightforward development process.

You can handle CSS design in a number of ways – using traditional CSS
files, modular approach, or style within JavaScript. Styled-components is a
nice example of a library that allows you to style elements in React.

Another way to separate logic from the layout is to create custom hooks
or use utilities like classnames() function in React.

It must be noted that separation of layout and logic doesn’t always lead
to shortest lines of code. Ultimately, the best way to organize your project
depends on needs of your web application and what it needs to accomplish.

Prioritize responsivity

Every modern web application needs to be responsive to make sure it runs
properly on any device, with screens large and small. That includes devices
like PC, laptop, tablet, smartphone, or even gaming consoles. Users don’t like
to scroll down, resize windows, or scroll across to see contents of the page.
Responsivity ensures they don’t have to. More and more people are using
smartphones to use web applications. Sometimes majority of your visitors are
going to be viewing your app on a small screen. In that case, responsivity
should be your N1 priority.

Responsivity can also increase search engine traffic. Google, Bing, and
majority of search engines evaluate responsivity to determine which pages to
show at the top. Responsive web apps tend to load faster as well, which is also
a positive SEO factor.

Building responsive web applications is also more efficient than building
separate apps for each device. As a result, you save a lot of money on
development costs of different apps.