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.

Routing

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.

https://simplefrontend.com/ternary-operators-in-react-use-cases-and-example.

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.

Props

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

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.