Introduction to react-router for beginners

React library is a great tool for building UIs. However, it’s not enough to build fully functional web applications. For one, it does not have routing – you can not set up functional navigation using React alone. For that, you need to install an external library called React Router. Nearly all React developers use this library. If you’re learning to write web applications in React, then learning React-Router is a must. It is likely to come in handy when you start on a real job as well.

You have probably noticed that different pages on certain apps load almost instantly. This is not magic, it’s called Single Page Applications, where everything you need to see is loaded at once. Then you are just ‘focused’ on various parts of the page. React Router makes it possible to go from one page to another, and change what you see depending on your navigation between different pages.

In this tutorial, you are going to learn fundamentals of how to do routing in React, including: what routing means, react-router DOM, and all the important custom components and hooks from the react-router library.


In simple words, routing is the ability to go from one page to another. It is not exclusive to single page apps (SPAs) but it is different in SPAs. In normal websites or web applications, the browser loads different files from external server and renders the new page. In SPAs, everything is already loaded, and browser simply shows you what you need to see for that specific route.

Routing includes basic navigation features – links to other pages on the same website, buttons that perform an action and redirect you to another page, and so on. All of this is included in routing.

The foundational principle of routing is matching of URLs. As a web developer, you define patterns for URLs and specify components that need to be shown to users if URL fits a specific pattern. URLs can have dynamic elements in them, like name of the product.

What is React Router DOM

To understand what is React Router DOM, first you need to know that React is used to build applications for browsers as well as native applications for smartphones. React-Native is, in a lot of ways, similar to React, but it’s used for building native apps for mobile phones.

Then what makes the React Router DOM different is its focus on web applications. It’s a significant portion of the entire react-router library dedicated specifically for building web apps. This doesn’t mean that apps with react-router DOM navigation can not be used on mobile phones. Mobile users can still navigate apps that use React Router DOM, as long as they use browsers in their phones. Native apps are entirely different, and navigating them requires use of other elements from React Router library.

Important Custom Components for Routing in React

React library is based on reusable components. Naturally, react-router library also provides a lot of important functionalities via custom components. You can import BrowserTouter, Route, Switch, Link, and other custom components. In fact, you need many of these custom components to set up a navigation in your app.

It’s easy to think of these custom components as being in three different categories: one is routers like <BrowserRouter>. This custom component works with browser’s history interface to adopt many of the important functionalities like pushState and replaceState for your react app. In order for all other components to work, the component tree must be wrapped with <BrowserRouter> component, as it provides important navigation features that are foundational for your React app.

Another category is that of route matchers, components like <Route> and <Switch> that are used to match routes with components, so React knows which components to display for a specified route. The <Switch> component is like switch case statement in JavaScript. It renders the first route that matches the specified pattern. It is best used if there are multiple patterns that might match the route.

Finally, the third category is that of navigation. This category includes custom components like <Link> and <Redirect>. The Link component is like <a> tag in HTML, as in it creates a link to another page, except it is compatible with SPA design. Unlike normal anchor tags in HTML, Link components simply take users to the specified URL and do not reload the page. The Link component accepts to prop to specify the relative path to navigate to. But that’s not the only thing you can do with <Link>. This article goes into depths on how to set onClick event handler on custom <Link> component.

Next, let’s move to important custom hooks in react-router.

useHistory, useParam, useLocation hooks

useHistory taps into browser’s native History API and gives you instance of history object. You can work with this instance to programmatically change the URL and perform many other useful actions for navigation. You can also access the history object to go back to previous page in React, or to redirect to another page in React.

URLs can have parameters in them. You broadly define the pattern and then the route component renders components depending on their parameters. useParam is another important hook that returns custom parameters for a specific instance of a rendered component. Access to search parameters can be useful to retrieve specific information about any specific instance of a component.

Finally, the useLocation hook return the latest URL in response to changes in the URL.

Final words

In this guide we walked you through most important custom components and hooks in react-router, and different roles these features play in building a navigation for your React app.

If you’re a beginner, a solid grasp on these concepts should give you a nice foundation, but it’s nowhere enough to implement navigation for complex apps in the real world. For that, you will need experience of building apps. In my personal opinion, SimpleFrontEnd is a great place to start your learning journey.

Starting front-end career as a self-taught front-end developer

Front-end developers create website interfaces that we interact with every day. There are thousands of businesses with their own front-end development teams, so there’s no shortage of vacancies for front—end developers. However, there is a shortage of qualified front-end developers who can write clean, error-free code. In this article, we will discuss how to start working as a front-end developer in 2022.

Learn necessary skills

Many companies are expecting front-end developers to have a college education, but majority of companies will hire you without one. One main important prerequisite is that you must demonstrate a strong knowledge of necessary skills.

To get a basic front-end developer job, you need to be proficient in three programming languages: HTML, CSS and JavaScript.

You can start learning via online courses, go to bootcamp or even hire a developer to mentor you. There are literally thousands of options for learning front-end development.

Practice writing code

Being an effective and efficient web developer comes down to writing error-free code. Debugging and fixing errors can take too much time. You can achieve mastery of any programming language by practicing it.

HTML is fairly easy, but CSS and especially JavaScript require many hours of practice to fully master.

Gain a competitive edge

Front-end development is a lucrative career, which means that there are a lot of candidates competing for junior positions. Starting a job as a junior developer is especially competitive because all employers are looking for experienced front-end development. There are only few positions where companies want to invest time and resources into developing a junior talent.

Having a competitive edge over other junior front-end developers can help you get the job and then advance your career faster than others. For example, it’s a very good idea to specialize in one JavaScript framework like React. You can go even further and learn features of React. For example, concepts like Virtual DOM, rendering, component reusability, or get current url in React.

Get experience

Experience doesn’t have to be of working at a full-time job. Start working on your own personal projects or, in ideal scenario, contribute to open-source projects. Becoming a contributor to one of the open-source projects can be prestigious and interviewers will look at it favorably. These projects usually have requirements for maintaining codebase and gradually adding code. Creating these open-source projects is a team effort, and if you’ve successfully established yourself as a member of a team, it means you can become a productive member of their developers team as well.

Create a portfolio

Having a portfolio of projects you worked on can be beneficial. You can show hiring managers the code you wrote and your CSS designs, for example. Needless to say, your portfolio should include the projects you’re most proud of. Creating projects for your portfolio can be an opportunity to practice. It takes time, but a good portfolio can significantly improve your chances of landing a job.

Have online presence

The most common problem of beginner front-end developers is that they don’t have online presence. Having a strong portfolio is only a part of that process. A blog can be a great tool for making yourself known and noticed on the internet. If you plan to become a contractor or freelancer, it can be a source of clients for you.

I personally ran a web development blog for 10 years, and I can say it has been one of the best decisions for my career. Let’s go over few reasons why blogging is good for your development as a web developer and obviously for the community as well.

Opportunity to learn

You don’t have to be an expert to start a front-end development blog. Everyone has expertise in certain area of front-end development. And in case you don’t think you are knowledgeable about anything, even better – it could be an opportunity to learn.

There’s a saying that you can only truly know something if you can explain it to others in simple words. Blogging is an easy way to explain things you think you know. If it turns out that you’re not as much of an expert as you thought, then writing about it will be an opportunity to gain an in-depth knowledge.

More importantly, keeping a blog can be an opportunity to learn writing as well. It is a useful skill because web developers not only have to write code, but also comments for one another.

Stay up to date on programming trends and technologies

Blogging about front-end development is a great way to stay updated on latest changes in your technology. It can also be an opportunity to explore other tech stacks and see if there’s anything else for your application.

Sometimes you will learn a new language or a new concept and have recruiters reach out to you. This is a guide that explains ternary operators, one of the most important concepts to understand.

Keep it focused

If you want people to follow your blog, write about one topic consistently. The focus of your blog can be very narrow, like one specific front-end framework. You could focus on React, for example. Alternatively, you can dedicate your blog to front-end development in general.

Be consistent

If you decide to publish weekly blog posts, stick with that plan. There is nothing more frustrating than expecting a new blog post and not getting it. If you anticipate that certain time will be difficult for you to write, then write in advance.

Writing technical tutorials in advance also gives you time to proofread them before publishing. It’s a bad idea to write something the day you plan on publishing it. It’s much better to proofread it the next day, or even three days later, to look at it with a fresh perspective.

Useful JavaScript concepts for building apps in React

Many newbie web developers look at salaries of React web developers and want to learn React right away. I hold the opinion that it’s better to master JavaScript first. All front-end frameworks are based on JavaScript anyway. If you master JavaScript (which is not an easy feat) you’ll have easier time learning front-end frameworks and UI libraries like React as well.

In this article, we will talk about most useful JavaScript concepts for building user interfaces in React.

Callback functions

ES6 introduced three great functions – map(), filter(), reduce(). If you’re going to build apps, you will use these all the time. map() allows you to iterate over array of objects to create elements and components in JSX.

React web apps often receive data as an array of objects. You can use map() to create real HTML elements using that data. Similarly, filter() takes a callback function argument as well. It returns a condition. Array items that meet the condition will be stored in the new array. This allows you to selectively create JSX elements based on a criteria.

reduce() is not used to create new elements. However, it is often used to aggregate certain values in the array. For example, add up all the numbers in the array.

Callback functions are also useful for using the useEffect() hook in React. Arguments to this function are callback functions, as well as dependency array. This guide explores how useEffect with no dependencies works.

Rest parameters

These allow you to define functions that accept flexible number of arguments. For example, you could specify what to do with first three arguments, and write something like …args. The function will take the first three arguments, and all remaining ones. Or the function could accept only this type of expandable number of arguments. It could be useful if you want a JavaScript function that adds up all numbers passed into it, for example.

Rest parameters are denoted by three dots before the argument name. Rest parameters must be the last in the order of arguments.

Rest parameters will help you write flexible event handlers that accept many parameters. Here’s a guide that explains how to pass a parameter to onClick in React.

Spread syntax

Beginner JavaScript programmers often confuse spread syntax with rest parameters. Both are denoted by three dots. However, REST is used when functions are defined. It allows us to expand the number of arguments.

Spread, on the other hand, allows us to ‘unpack’ everything from iterable values like arrays and strings. For example, when you’re calling an array, you can use the spread syntax to pass every item in the array as an argument. When defining a function, you use the REST operator to accept unpredictable number of items in the array.

Spread syntax is often used to combine items from two arrays. Let’s look at an example:

let arr1 = [a,b,c]

let arr2 = [d,e,f]

let combined = […arr1, …arr2]

The combined variable will be an array that contains all items from arr1 and arr2 arrays.

Ternary operators

One last great feature for conditional expressions are ternary operators. They allow you to evaluate a JavaScript expression (even a Boolean value) and return certain value if it is true, and other value if it’s false.

Ternary operators are often used in React. For conditional rendering, conditional classNames, conditional styles. It is used to add dynamic functionality to web applications.

You can even nest multiple ternary operators into one.

Where to learn necessary skills

Front-end development means building websites with beautiful design and sometimes dynamic features. Most of the complex web applications you visit every day – Facebook, Netflix and Disney plus are created more or less the same principles.

There are three main skills to developing websites – CSS, HTML and JavaScript. HTML is used for writing markup. In other words, creating elements to define a structure for the page. CSS is used for customizing the appearance of elements created with HTML. By extension, it can be used to design the entire website. Lastly, JavaScript is used for implementing dynamic features of a web application. For example, collecting user data, doing dynamic analysis, loading external data and other use cases for implementing business logic.

Learning HTML and CSS

Let’s discuss learning HTML and CSS. HTML is considered to be simpler of the two, while CSS appears simple, it’s complex.

For starters, you should attempt to learn CSS and HTML on freeCodeCamp, which is a great free resource for learning front-end development. It has all the necessary tools to help you learn these skills. You can practice writing actual HTML and CSS code, and solve actual challenges like building a simple static website.

Free resources are good place to start because you can get started without too much investment. Another great website is Codecademy, which explains CSS and HTML concepts in detail and takes you through the steps of learning as you write the code.

Learning Javascript

Next, it’s time to learn JavaScript. In this case, freeCodeCamp is a good place to start. It can give you a solid knowledge of JavaScript to get started. In addition to that, you can read free online book like ‘Eloquent JavaScript’, which is recognized as one of the great resources for learning JavaScript. There are dozens of other courses that teach JavaScript, so it’s hard to choose the right one.

Learning front-end frameworks

In case you don’t know, modern web applications are developed with JavaScript front-end frameworks like React or Angular. These frameworks provide a foundation for performing common web development tasks. You can simplify your life by using them.

To maximize your chances of landing a job, it’s preferable if you have a specialization in one of the frameworks. There are many great courses and websites that aim to teach you programming. Sometimes these websites and even courses have free and paid versions, so you can try it out before paying.

Front-end masters is considered to be one of the best resources for learning front-end development. They offer discounts in some cases.

Learn from documentation

Once you nail basics of one of these front-end frameworks, you can move on to official documentation of these languages. All three of them – Vue, React and Angular have excellent documentation to teach you programming in these languages.

Written documentation is a bit impersonal, and tutorials may be better if you prefer a personal touch.

Differences between state and props in React – breakdown

React didn’t become the most popular JavaScript library by chance. React has a number of unique features that make it a perfect choice for building interactive applications for the web. In this blog post, I want to talk about arguably two of the most integral features to building apps with React – state and props.

You will learn what state and props are and understand similarities and differences between them. We will also see how to pass data into components using props, and what are the shortcomings of using props to pass data down multiple levels. We will also learn about state and React’s rules when it comes to dealing with state values.


As you know, React is founded on reusability of components. The idea is that you define component once, and define its overall structure. The you pass in different bits of data to ‘fill’ in the blanks, so the repeated parts of UI (let’s say cards for different products) have the same structure, but display different information. This way, you don’t have to write markup structure for every individual instance of that particular UI component. In simple words, props allow you to pass data into components, which are pre-defined bits of UI. Components use this data to fill in the blanks, and thus customize their content, appearance, or sometimes even their functionality.

The syntax for passing down props in JSX is quite similar to element attributes in HTML. You can even think of props as custom attributes for React elements. Except unlike in HTML, the individual components have much more control and can do a lot more with the data that’s passed into them.

Let’s look at an example:

<Component text=”Hello World” />

In this case, parent component passed down a simple string via text prop. The child component’s definition can tap into its text prop and display it on the page. This may seem useless, but you can technically replace text with any other value and use it to customize contents of the component.

Let’s look at the child component definition and structure:

Function Component (props) {

Return (<p>{props.text}</p>)


As you can see, functional component accept props as an argument, and the text prop is passed down as an individual property of props object. We use curly braces to embed a JavaScript expression inside JSX, and access text property of the props object.

Thinking of props as arguments to the component can be an useful way to understand them. Like arguments, props are inputs into the component that can be helpful in getting the result we wont. And like functions, components save us from writing the same lines of code over and over again.

Many external libraries that provide ready-made components use props as a way to customize various aspects and even content of these components. For example, ‘react-router’, the main routing library for React, provides a custom <Navigate> component. It is often used with React forms to redirect users to another page when the form is submitted. Passing it a ‘to’ prop allows us to specify the URL to which users should be redirected.

An important feature of props is that they are uni-directional. Parent components can pass down props into the child components invoked within their JSX. Child components can only receive props, and can not modify or delete them. Uni-directional data flow is an extremely important feature that ensures consistency of data across multiple React components.


State is another very important feature of React. To explain it in simple words, state maintains the record of what’s going on in the app. Is the ‘dark mode’ toggle selected or not selected? What is current value in the input field? Should the component be expanded or collapsed? State keeps track of everything, and it is what makes it possible to implement these dynamic features.

State is especially important for handling user inputs. It is essential in onChange event handlers to handle changes in the text inputs in React.

State is an internal management tool, as opposed to props that deal with relationship between multiple components. However, data passed down via props often comes from the state.

Before React version 16, only class components could initialize the state. Functional components were relegated purely to presentational role. Since the introduction of hooks, that has changed, with functional components now being able to initialize state variables using the useState() hook.

If you’re a beginner, I personally recommend you work with functional components and variables created with useState hook. I recommend this because the hook keeps things simple – it returns two variables – one to hold the state value, and another to update it if necessary. You don’t have to deal with setState() method as you do in class components.

Unlike props, changing state is encouraged and even necessary. The entire purpose of state is to update values in response to user events, or other external events (like loading data from external API).

Importantly, changes to the state re-render lead the component to re-render itself and all of its children components. This behavior may seem extreme, but it’s necessary to make sure the app responds to latest changes. Plus, React uses Virtual DOM, so re-rendering all components is not a very expensive computation.

Differences between state and props

Let’s finally summarize most important distinctions between state and props.

  • By design, state is meant to change according to most recent user interactions or other external events. Props can not be mutated by the child component that receives data via props.
  • Props are external, state is internal data.
  • Props are uni-directional, meaning that parent components can pass data down to their children using props. Children can not pass data back up. However, they can invoke event handlers passed down to them via props, and effectively update state values in the parent component.
  • The only way to change props is to change it in the parent component that invokes the child component. The only way to change state is to use either setState() method or special function for updating a specific state variable.

State and props are without a doubt, two of the most important features to understand if you want to effectively build web applications with React. They underpin the entire React ecosystem.

Cruising as a family – tips and tricks

It can be scary to go on a cruise for the first time. The concept is pretty different from any travel you might’ve done, so you don’t know what to expect. Still, there are lots of cruise lines that offer family packages and will take good care of you. You only need to know how to find them. So without further ado, this is everything you need to know before booking your first family cruise.

Facilities onboard

Family cruises are a  good opportunity to spend quality time with your children as well as parents. But not everyone in the family is interested in the same thing. You want to book a cruise that offers wide variety of facilities, from dining to sports activities and outdoors facilities like swimming pool. Some cruise ships also have movie theaters and even offer theatre performances. There are also usually variety of dining options, from guilty pleasure fast food to restaurants with a more classy atmosphere.

Finally, most cruise ships have several swimming pools of different sizes and shapes. Swimming is something your entire family can enjoy, so don’t forget to pack a swimsuit. Cruises have plenty of space on the deck, so cruising is a perfect opportunity to sunbathe as well.

Make sure to pack swimsuits to enjoy everything cruises have to offer. Also pack any gear that may be necessary to enjoy activities onboard. I personally recommend getting a custom cruise t-shirts for families to add a bit of fun.

Dining facilities

Personally, I love traveling because it allows me to have delicious local meals and try new things. When you’re on a cruise, you spend most of your time on the ship, but best cruise ships have restaurants that serve meals from different cuisines and prepare them to perfection. Cruise food is not similar to airplane food, It is much better.

A cruise should have food options for everyone – children as well as seniors. For example, P&O cruises offer a buffet so you can walk up and grab a snack. There is no dress code, most important thing is that you eat. These buffets offer a variety of food – burgers, sandwiches, and even pizza. These buffets are included in the cost, so you can satisfy your hunger for no additional price.

There are plenty of specialty restaurants as well. You can go as a whole family and try your favorites. Or you can make use of children’s restaurants with playgrounds, and adults go to a nearby restaurant to enjoy a nice meal.


Cruise ships offer a number of other experiences as well. Last year we went on a cruise that offered rope-walking experience 50 meters above the ocean. It was very safe, but also thrilling to literally walk a tightrope. I’ve also seen mini golf court, but did not take part in it. A lot of families were playing mini golf and it seemed like something that would be a lot of fun for a whole family. Cruise ships also have various tech gadgets as well as card games and puzzles, so everyone can find something to do.


Over the course of several days, cruise ships can take you to many wonderful destinations that you wouldn’t have chance to see otherwise. Last year we saw several Italian seaside cities this way. Sometimes ships stop at a port for a long time. If you want to spend time exploring local places, book a cruise that stops for at least a full day.

Going on a cruise with friends – everything you need to know

What’s more fun than a group of good friends sharing an adventure together. Friends’ cruise can be a lot of fun, but you need to prepare to avoid common mistakes and have a good time. In today’s article I will share my experiences of cruising with a group of friends, and tell you what to do, not to do, and how to get the most out of your time on a cruise.

Don’t make strict schedule

If you’re the one organizing the trip, its natural to want to make sure that everyone sees and partakes in best activities on the ship. However, everyone is different and comfortable with different pace of activities. Some of your friends might get tired quickly, while others will want to keep going late into the evening. So its best to have general idea of what facilities and activities the ship has to offer, and take it from there. This way, its more adventurous and spontaneous. It also takes less effort on your part.

Together time

When cruising together, its important to spend time and make memories together, but also not restrict people and give them freedom to do what they want. My personal favorite principle is to make an agreement that we will have breakfast and dinner as a group, and then have rest of the day free to do what we want. That doesn’t always mean that we will spend rest of the day separately. Often times we stick together and partake in activities cruise ship has to offer. Few people might go off on their own business, and that’s perfectly understandable. Or they might go in groups of twos or three people. Not everyone can agree on the best course of action. Plus having this guideline means that everyone is together in the dinner time, and that’s enough to make memories that include everyone.


Flexibility is good, but it doesn’t mean to leave everything to chance. At least few members of the group should be aware of accomodations and facilities available on the ship, and choose accordingly. Then they can share their knowledge while on board and help everyone get introduced to their ship. Its also a good idea to have custom t-shirts for group of friends on a cruise. It can be a fun conversation starter while you’re on the cruise, and serve as memorabilia after the trip is over.

Take excursions

Many cruise ships make stops at various ports around the world. Our cruise stopped for a day on Greek Islands. It was some of the most beautiful islands you’ll ever find anywhere. Cruises can pack a lot of fun, but getting off the boat can be a great adventure as well. Be sure that at least one of you has an eSIM or roaming data, so you can stay connected. Also, if you do venture off, everyone should bring a passport.

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.