https://www.makeuseof.com/redirect-user-after-login-react/
How to Redirect a User After Login in React
UPDATED MAR 9, 2023
Learn how to redirect a user from a restricted page to the login page and again redirect to the original page after logging in.
Readers like you help support MUO. When you make a purchase using links on our site, we may earn an affiliate commission. Read More.
Usually, when building web applications, login pages are used to protect private pages. For example, for a blogging platform, the dashboard may only be accessible to authenticated users. If an unauthenticated user tries to access that page, the application redirects them to the login page. Once they are logged in, they get access.
MAKEUSEOF VIDEO OF THE DAY
We will look at how you can redirect a user from a restricted page to a login page. We will also discuss how you can return the user back to the page they were on after logging in.
Create a React Application
In React Router v6, there are two ways you can use to redirect a user — the Navigate component and the useNavigate() hook.
To see how they work, first, create a React application using the create-react-app command.
npx create-react-app react-redirect
Create a Login Page
You will need to create a Login page to authenticate users. For simplicity, you'll use an array of objects as the user database.
Create a new file in the src folder and name it Login.js. Then add the following code, to create the login form.
import { useState } from "react";
import Dashboard from "./Dashboard";
const Login = () => {
const [username, setusername] = useState("");
const [password, setpassword] = useState("");
const [authenticated, setauthenticated] = useState(localStorage.getItem(localStorage.getItem("authenticated")|| false));
const users = [{ username: "Jane", password: "testpassword" }];
const handleSubmit = (e) => {
e.preventDefault()
const account = users.find((user) => user.username === username);
if (account && account.password === password) {
setauthenticated(true)
localStorage.setItem("authenticated", true);
}
};
return (
<div>
<p>Welcome Back</p>
<form onSubmit={handleSubmit}>
<input
type="text"
name="Username"
value={username}
onChange={(e) => setusername(e.target.value)}
/>
<input
type="password"
name="Password"
onChange={(e) => setpassword(e.target.value)}
/>
<input type="submit" value="Submit" />
</form>
</div>
)
};
}
export default Login;
This is a simple login form. When a user submits their username and password, the application compares the data to array data. If the user details are in the array, the application sets the authenticated state for that user to true.
Since you will be checking if the user is authenticated in the Dashboard component, you also need to store the authentication status somewhere that can be accessed by other components. This article uses local storage. In a real application, using React context would be a better choice.
Create a Dashboard Page
Create a file named Dashboard.js and add the following code to create the Dashboard component.
const Dashboard = () => {
return (
<div>
<p>Welcome to your Dashboard</p>
</div>
);
};
export default Dashboard;
The dashboard should only be accessible to authenticated users only. Therefore, when users visit the dashboard page, first check whether they are authenticated and if they aren't, redirect them to the login page.
To do this, you'll need to set up the application routes using React router, so install react-router-dom via npm.
npm install react-router-dom
Then, in index.js, create the routes.
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Login from "./Login";
import Dashboard from "./Dashboard";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<BrowserRouter>
<Routes>
<Route index element={<App />} />
<Route path="login" element={<Login />} />
<Route path="dashboard" element={<Dashboard />} />
</Routes>
</BrowserRouter>
</React.StrictMode>
);
Protect the Dashboard Page
Now that your application routes are set up, the next step is to make the dashboard route private. When the Dashboard component loads, it retrieves the authentication from the local storage and stores it in the state. It then checks if the user is authenticated. If they're authenticated, the application returns the dashboard page otherwise it redirects them to the login page.
import { useEffect, useState } from "react";
const Dashboard = () => {
const [authenticated, setauthenticated] = useState(null);
useEffect(() => {
const loggedInUser = localStorage.getItem("authenticated");
if (loggedInUser) {
setauthenticated(loggedInUser);
}
}, []);
if (!authenticated) {
// Redirect
} else {
return (
<div>
<p>Welcome to your Dashboard</p>
</div>
);
}
};
export default Dashboard;
Redirect User to Login Page Using Navigate
To redirect the user, you need to use the Navigate component. Note that this component replaced the Redirect component used in React Router v5.
Import Navigate from react-router-dom.
import { Navigate } from "react-router-dom";
Then use it as follows to redirect unauthenticated users.
if (!authenticated) {
return <Navigate replace to="/login" />;
} else {
return (
<div>
<p>Welcome to your Dashboard</p>
</div>
);
}
The Navigate component is a declarative API. It relies on a user event, which in this case is authentication to cause a state change and consequently cause a component re-render. Note that you don't have to use the replace keyword. Using it replaces the current URL instead of pushing it to the browser's history.
Redirect User to Another Page Using useNavigate()
The other option for performing redirects in React is the useNavigate() hook. This hook provides access to the navigate imperative API. To use it, start by importing it from react-router-dom.
import { useNavigate } from "react-router-dom";
After login, redirect the user to the dashboard page using the handleSubmit() function as shown below:
const navigate = useNavigate();
const Login = () => {
const navigate = useNavigate();
const [username, setusername] = useState("");
const [password, setpassword] = useState("");
const [authenticated, setauthenticated] = useState(
localStorage.getItem(localStorage.getItem("authenticated") || false)
);
const users = [{ username: "Jane", password: "testpassword" }];
const handleSubmit = (e) => {
e.preventDefault();
const account = users.find((user) => user.username === username);
if (account && account.password === password) {
localStorage.setItem("authenticated", true);
navigate("/dashboard");
}
};
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
name="Username"
value={username}
onChange={(e) => setusername(e.target.value)}
/>
<input
type="password"
name="Password"
onChange={(e) => setpassword(e.target.value)}
/>
<input type="submit" value="Submit" />
</form>
</div>
);
};
In this example, once the user submits the form with the correct details, they are redirected to the dashboard.
Note that when creating applications, one of the goals is to give users the best experience. In this case, taking the user back to the page they were on before redirecting them to the login page improves user experience. You can do this by passing -1 to navigate like this, navigate (-1).
Routing in React
In this article, you learned how you can redirect a user to another page in React using both the Navigate component and the useNavigate() hook. Use this information to create an authentication flow for your own app where you redirect unauthenticated users from a protected page to the login page.
RELATED TOPICS
ABOUT THE AUTHOR
Mary Gathoni(99 Articles Published)
Mary is a staff writer at MUO based in Nairobi. She has a B.Sc in Applied Physics and Computer Science but enjoys working in tech more. She has been coding and writing technical articles since 2020.
How to Create a Protected Route in React
UPDATED MAR 4, 2023
Preventing unauthorized users from accessing your React page is critical for security. Here's how to do it.
Readers like you help support MUO. When you make a purchase using links on our site, we may earn an affiliate commission. Read More.
Protected routes are routes that allow access to authorized users only. This means that users must first meet certain conditions before accessing that specific route. This is essential for securing certain routes or information. There are various ways you can use protected routes in React. One of them is using a higher-order component that wraps a protected route and checks if a user is authenticated before rendering a component.
MAKEUSEOF VIDEO OF THE DAY
Creating a React Application
Before creating the protected route, you'll need to create a React app.
Run the command below to use the create-react-app command tool to bootstrap the application.
npx create-react-app protect-routes-react
The create-react-app command will create a folder named protect-routes-react containing all the necessary files and packages to get started.
Navigate to the folder and run npm start to start the application.
cd protect-routes-react
npm start
Open your application folder with your preferred text editor and modify App.js so that it only contains the following code.
function App() {
return <div></div>;
}
export default App;
You are now ready to set up the routes.
Setting Up the React Router
Run the npm command below in the terminal to install react-router-dom.
npm install react-router-dom
In this application, you will create three main pages:
- Home page (the landing page).
- Profile page (protected, so only logged-in users have access).
- About page (public so anyone can access it).
To start, create a component named Navbar.js. This component will contain the navigation links to the three pages.
In this file, import the Link component from react-router-dom and add the links.
const { Link } = require("react-router-dom");
const Navbar = () => {
return (
<nav style={{ textAlign: "center", marginTop: "20px" }}>
<Link to="/" style={{ padding: "10px" }}>
Home
</Link>
<Link to="/profile" style={{ padding: "10px" }}>
Profile
</Link>
<Link to="/about" style={{ padding: "10px" }}>
About
</Link>
</nav>
);
};
export default Navbar;
After creating the links, create the matching routes in App.js.
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Navbar from "./Navbar";
import Home from "./Home";
import Profile from "./Profile";
import About from "./About";
function App() {
return (
<Router>
<Navbar />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/profile" element={<Profile />} />
<Route path="/about" element={<About />} />
</Routes>
</Router>
);
}
export default App;
Next, create the components you have referenced in App.js.
In Home.js add the following code to create the home page.
const Home = () => {
return <h1>Home page</h1>;
};
export default Home;
In Profile.js add the following code to create the profile page.
const Profile = () => {
return <h1 style={{ textAlign: "center" }}>Profile Page</h1>;
};
export default Profile;
Finally, in About.js, add the following code to create the about page.
const About = () => {
return <h1 style={{ textAlign: "center" }}>About page</h1>;
};
export default About;
Once you've created the pages, you can now create the protected routes.
Creating Protected Routes in React
The /home and /about routes are public routes meaning anyone can access them, but only authenticated users can access the profile route. You, therefore, need a way to log in as a user.
Setting Up Fake Authentication
Since this is not an authentication tutorial, you will use React useState hook to simulate a login system.
In App.js, add the following.
import { Routes, Route, BrowserRouter } from "react-router-dom";
import { useState } from "react";
<em>// Other import stamements</em>
function App() {
const [isLoggedIn, setisLoggedIn] = useState(null);
const logIn = () => {
setisLoggedIn(true);
};
const logOut = () => {
setisLoggedIn(false);
};
return (
<BrowserRouter>
<Navbar />
{isLoggedIn ? (
<button onClick={logOut}>Logout</button>
) : (
<button onClick={logIn}>Login</button>
)}
<Routes>
</Routes>
</BrowserRouter>
);
}
export default App;
Here, you are tracking the login status of the user using state. You have two buttons, the login, and the logout button. These buttons are rendered in turn depending on whether a user is logged in or not.
If the user is logged out, the login button is displayed. Clicking on it will trigger the login function which will update the isLoggedIn state to true and in turn the display from login to the logout button.
Protecting Private Components
To protect routes, the private components must also have access to the isLoggedIn value. You can create a new component that accepts the isLoggedIn state as a prop and the private component as a child.
For instance, if your new component is named Protected, you would render a private component by wrapping it like this:
<Protected isLoggedIn={isLoggedIn}>
<Private />
</Protected>
The Protected component will check whether isLoggedIn is true or false. If it's true, it will go ahead and return the Private component. If it's false, it will redirect the user to a page where they can log in.
Learn more about other ways you can use to render a component depending on conditions from this article on conditional rendering in React.
In your application, create a file named Protected.js and add the following code.
import { Navigate } from "react-router-dom";
const Protected = ({ isLoggedIn, children }) => {
if (!isLoggedIn) {
return <Navigate to="/" replace />;
}
return children;
};
export default Protected;
In this component, the if statement is used to check whether the user is authenticated. If they are not, Navigate from react-router-dom redirects them to the home page. However, if the user is authenticated, the component renders the children.
To protect the Profile route, wrap it with the Protected route and pass in the isLoggedIn state as a prop.
<Route
path="/profile"
element={
<Protected isLoggedIn={isLoggedIn}>
<Profile />
</Protected>
}
/>
The App component should now look like this.
import { Routes, Route, BrowserRouter } from "react-router-dom";
import { useState } from "react";
import Navbar from "./Navbar";
import Protected from "./Protected";
import Home from "./Home";
import About from "./About";
import Profile from "./Profile";
function App() {
const [isLoggedIn, setisLoggedIn] = useState(null);
const logIn = () => {
setisLoggedIn(true);
};
const logOut = () => {
setisLoggedIn(false);
};
return (
<BrowserRouter>
<div>
<Navbar />
{isLoggedIn ? (
<button onClick={logOut}>Logout</button>
) : (
<button onClick={logIn}>Login</button>
)}
<Routes>
<Route path='/' element={<Home />} />
<Route path='/profile'
element={
<Protected isLoggedIn={isLoggedIn}>
<Profile />
</Protected>
}
/>
<Route path ='/about' element={<About />} />
</Routes>
</div>
</BrowserRouter>
);
}
export default App;
That's it on creating protected routes. You can now access the profile page only if you are logged in. If you try to navigate to the profile page without logging in you will be redirected to the home page.
Role-Based Access Control
Protected routes in React help you restrict unauthenticated users from accessing a page. This is very basic and in some cases, you might need to go even further and restrict users based on their roles. For instance, you can have a page say an analytics page that only grants access to admins. Here, you will need to add logic in the Protected component to check whether a user needs access to that route based on their role.
RELATED TOPICS
ABOUT THE AUTHOR
Mary Gathoni(99 Articles Published)
Mary is a staff writer at MUO based in Nairobi. She has a B.Sc in Applied Physics and Computer Science but enjoys working in tech more. She has been coding and writing technical articles since 2020.
How to Implement Conditional Rendering in React.js (With Examples)
PUBLISHED FEB 25, 2022
Conditional rendering is a useful way to improve your app. Here are a selection of ways to use it.
Readers like you help support MUO. When you make a purchase using links on our site, we may earn an affiliate commission. Read More.
Conditional rendering refers to changing the behavior of an app depending on its state. For instance, you can change the greeting message of your React app to dark during the night. This way you have a different display message depending on the time of day.
Conditional rendering allows you to render different React components or elements if a condition is met. In this tutorial, you are going to learn about the different ways you can use conditional rendering in React.js applications.
MAKEUSEOF VIDEO OF THE DAY
Ways You Can Implement Conditional Rendering
To follow along with these examples, you need to have a basic understanding of how React works. If you're struggling in that instance, don't worry—we've got a useful beginner's guide to React.js.
Using Conditional Statements
Like in JavaScript, you can use conditional statements like if…else to create elements when certain conditions are met.
For example, you can display a specified element in the if block when a condition is met and display a different one in the else block if the condition is not met.
Consider the following example that either displays a login or logout button depending on the login status of the user.
function Dashboard(props) {
const { isLoggedIn } = props
if(isLoggedIn){
return <button>Logout</button>
} else{
return <button>Login</button>
}
}
This function renders a different button depending on the isLoggedIn value passed as a prop.
RELATED:How To Use Props In ReactJS
Alternatively, you can use the ternary operator. The ternary operator takes in a condition followed by the code to execute if the condition is truthy followed by the code to execute if the condition is falsy.
Rewrite the above function as:
function Dashboard(props) {
const { isLoggedIn } = props
return (
<>
{isLogged?<button>Logout</Logout>:<button>Login</button>)
</>
)
}
The ternary operator makes the function cleaner and easier to read compared to the if…else statement.
Declaring Element Variables
Element variables are variables that can hold JSX elements and be rendered when required in a React app.
You can use element variables to render only a certain part of the component when your application meets the specified condition.
For example, if you want to render only a login button when the user is not signed in and a logout button only when they are signed in, you can use element variables.
function LoginBtn(props) {
return (
<button onClick={props.onClick}>
Login
</button>
);
}
function LogoutBtn(props) {
return (
<button onClick={props.onClick}>
Logout
</button>
);
}
function Dashboard() {
const [loggedIn, setLoggedIn] = useState(true)
const handleLogin = () => {
setLoggedIn(true)
}
const handleLogout = () => {
setLoggedIn(false)
}
let button;
if (loggedIn) {
button = <LogoutBtn onClick={handleLogout}/>
} else {
button = <LoginBtn onClick={handleLogin}/>
}
return (
<>
{loggedIn}
</>
)
}
In the above code, first created the Login and Logout button components then define the
In this component, use React state hook to keep track of when the user is logged in.
RELATED:Master Your React Skills By Learning These Additional Hooks
Now, depending on the state either render the
If the user is not logged in, render the
Using Logical Operators
You can use logical && operator to conditionally render an element. Here an element is rendered only if the condition evaluates to true otherwise it is ignored.
If you want to notify a user of the number of notifications they have only when they have one or more notifications, you can use the following.
function ShowNotifications(props) {
const { notifications } = props
return (
<>
{notifications.length > 0 &&
<p>
You have {notifications.length} notifications.
</p>
}
</>
)
}
Next, to render an element if the logical && expression evaluates to a false value, chain the logical || operator.
The following function displays the “You have no notifications” message if no notifications are passed as props.
function ShowNotifications(props) {
const { notifications } = props
return (
<>
{notifications.length > 0 &&
<p>
You have {notifications.length} notifications.
</p> || <p>You have no notifications</p>
}
</>
)
}
Prevent a Component From Rendering
To hide a component even though it was rendered by another component, return null, instead of its output.
Consider the following component that only renders a warning button if a warning message is passed as props.
function Warning (props) {
const {warningMessage} = props
if (!warningMessage) {
return null
}
return (
<>
<button>Warning</button>
</>
)
}
Now, if you pass in ‘warningMessage’ to the
<Warning warningMessage="Warning message"/> // the warning button is rendered
<Warning/> // the warning button is not rendered
Examples of Conditional Rendering in Real-Life React Applications
Use conditional rendering to accomplish different tasks in your application. Some of those include rendering API data only when it is available and displaying an error message only when an error exists.
Rendering Data Fetched from an API in React
Fetching data from an API can take a while. Therefore, first, check if it's available before using it in your application otherwise React will throw an error if it's not available.
The following function shows how you can conditionally render data returned by an API.
function FetchData() {
const [data, setData] = useState(null);
const apiURL = "https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY";
// Fetch data from API using Axios
const fetchData = async () => {
const response = await axios.get(apiURL)
// Update state with the data
setData(response.data)
}
return (
<>
<h1>Astronomy picture of the day</h1>
{
data &&
<p>{data.title}</p>
<p>{data.explanation}</p>
}
</>
)
}
In the above function, fetch the data from the NASA Apod API using Axios. When the API returns a response, update the state and use logical && operator to only render the data only when it's available.
RELATED:How To Consume APIs In React Using Fetch And Axios
Displaying Error Messages
In cases where you want to display an error only when it exists, use conditional rendering.
For instance, if you are creating a form and want to display an error message if a user typed in the wrong email format, update the state with the error message and use an if statement to render it.
function showError() {
const [error, setError] = useState(null)
return (
<>
{
if (error) {
<p>An error occurred: {error}</p>
}
}
</>
)
}
Choosing What to Use in Your React App
In this tutorial, you learned about the several ways who can conditionally render JSX elements.
All the methods discussed provide the same results. Make a choice on what to use depending on the use case, and the level of readability you want to achieve.
RELATED TOPICS
ABOUT THE AUTHOR
Mary Gathoni(99 Articles Published)
Mary is a staff writer at MUO based in Nairobi. She has a B.Sc in Applied Physics and Computer Science but enjoys working in tech more. She has been coding and writing technical articles since 2020.
https://www.makeuseof.com/how-to-use-chatgpt-
7 Best Free Tutorials for Learning React and Making Web Apps
BYJOEL LEE
PUBLISHED MAR 28, 2017
Free courses are rarely as comprehensive and helpful — but we've found several React courses that are excellent and will get you started on the right foot.
Readers like you help support MUO. When you make a purchase using links on our site, we may earn an affiliate commission. Read More.
Right now, not only is React at the height of its popularity, but its popularity is accelerating. As far as JavaScript web development is concerned, React is one of the easiest frameworks to learn and one of the most effective for rapid and robust development.
So if you've decided to learn it, pat yourself on the back: you've made a smart choice.
MAKEUSEOF VIDEO OF THE DAY
The only problem is that most worthwhile React courses come with a hefty price tag. For example, the highly-acclaimed
React for Beginners course is
1. React Training's Fundamentals Course
Tyler McGinnis is a well-known React developer and instructor who has been teaching and writing about React for years now. He currently has four courses available on React Training [No Longer Available], the first of which is completely free and serves as an entry point for the others.
React Fundamentals is divided into 32 video lessons that add up to three full hours of education. You'll learn everything you need to get a basic React app up and running (i.e. React ecosystem, NPM, Babel, and Webpack), the core concepts and lifecycle that drive React apps, how to write components properly, and how to pass data around.
It's dense. It's informative. It's the perfect introduction, and the fact that McGinnis offers it for free is pretty awesome. This should be your first stop when learning React.
Website — React Fundamentals Course [No Longer Available]
2. Hacking With React
Hacking With React is an ebook that's completely free, cover to cover, if you read the web-only version. You can grab a downloadable PDF, EPUB, or MOBI version of it for $10 if you'd rather take it with you and learn offline. Either way, it's an awesome resource for starters who don't like videos.
It starts at the very beginning, explaining basic concepts like JSX and components and props, and holds your hand while graduating to intermediate topics like states, routing, tests, linting, and more. It's written in ES6 start to finish and you'll learn best practices along the way, including Babel, Webpack, and ESLint.
Will it make you a React expert? No, but it will get you comfortable enough to feel confident and keep learning. At the very least, you'll know more than enough React to decide whether to spend money on an advanced premium course elsewhere.
Website — Hacking With React
3. The Official React Tutorial
You'd think that the official tutorial should be the first place to look to learn React, but I personally found it a bit too fast for complete newbies — it assumed a lot more knowledge than most newbies have. It's perfect if you've had previous experience with another JavaScript web framework.
That being said, the official React tutorial is fantastic once you've learned the core concepts of React and are struggling to put them into practice. It takes you through the creation of a tic-tac-toe web app using nothing more than components, props, and state. It bridges the gap between abstract theory and practical application.
I also recommend checking out the official React documentation, which explains every bit of React in surprising amount of detail. In particular, the Thinking in React page is like a mini-tutorial on grasping the idioms that drive React. Don't be afraid to refer back to the React documentation over and over again as you learn and create your own apps.
Website — The Official React Tutorial and Thinking in React
4. Egghead's React Fundamentals Course
Egghead offers dozens of courses (hundreds of lessons) on various web development topics: JavaScript, Angular, React, RxJS, Node, TypeScript, etc. React is the third largest topic on the site, and although most of the courses are for premium users, there are five available for free:
- Start Using React to Build Web Applications
- Add Routing to React Apps Using React Router v4
- Getting Started With Redux
- Building React Applications With Idiomatic Redux
- Manage Complex State in React Apps With MobX
The first two are the most important, but you will probably want to take all of them at some point (optimally in the order listed). The courses assume you already know JavaScript, so check out Egghead's JavaScript courses if you aren't comfortable with the language yet.
Note that the premium courses are pretty good too, and they're worth checking out if you can afford the Pro
subscription:
Website — Egghead's React Fundamentals Course
5. Learn React and Redux With Cabin
Though Redux isn't part of the core React framework, they're so often used together that you really should learn it. And even if you eventually move away from Redux, you can take the concepts with you and apply them to whatever you end up using in its stead.
Cabin is a 10-part tutorial series that will teach you how to create a simplified social network app from scratch: installing Node/React/Webpack, understanding how React works, incorporating Redux, dealing with social network features like feeds and notifications, processing images and filters like Instagram, and more.
The last part is an overview of "best practices" that not only teaches you the most effective way to use and organize React/Redux, but also common mistakes to avoid, how to design a scalable app, and how to use third-party tools to ease your development workflow.
Website — Learn React and Redux With Cabin
6. LearnCode Academy's React Course
Over the last few years, LearnCode Academy has distinguished itself as one of the best programming channels on YouTube. It specialized in web development and covers all kinds of topics ranging from HTML, CSS, and JavaScript to specific frameworks like Angular and React. And it's all free.
The course is divided into three sections: eight videos on core React concepts, six videos on using Flux for data architecture, and seven videos on using Redux to manage state. All of this is done using up-to-date practices, including ES6 and Webpack.
Note that this isn't a comprehensive course, and Flux and Redux are both advanced concepts that aren't part of the core React framework, so we recommend using this course as a way to revisit and cement concepts learned in the courses above.
Website — LearnCode Academy's React Course
7. The React Convention
Some programmers prefer to code by convention — that is, adhering to a certain set of design decisions ("conventions") from project to project to minimize complexity and speed up the development process, particularly in the early stage of new projects. This online ebook aims to present one kind of convention that React developers can follow.
Before you dive into this, however, you should already be well-versed in ES6, comfortable with the React framework, and understand the basics of Redux. This ebook isn't for newbies per se. Rather, it's helpful for intermediates who feel overwhelmed and aren't sure how to turn their React/Redux knowledge into web apps from scratch.
The tutorial starts off with a starter kit project and shows you how to modify it. By following this convention in future projects, you won't need to waste time recreating everything.
Website — The React Convention
So You've Learned React: Now What?
With these tutorials under your belt, you should be more than knowledgeable enough to start making your own web apps with React. At this point, all that's left is to practice, practice, practice. And what's particularly cool is that you can later use React Native to create mobile apps — but don't get ahead of yourself. Stick with web apps until you're confident.
It's going to be a tough road, so we recommend checking out our article on learning how to program without stress. Just because you're struggling doesn't mean you aren't cut out to be a programmer!
For more learning, check out the best courses worth paying for on Coursera.
Hopefully these free tutorials helped! If you know of any other free React resources that we missed, please let us know in a comment down below.
Image Credit: guteksk7 via Shutterstock.com
RELATED TOPICS
ABOUT THE AUTHOR
Joel Lee(1449 Articles Published)
Joel Lee was formerly the Editor in Chief of MakeUseOf from 2018 to 2021. He has a B.S. in Computer Science and over nine years of professional writing and editing experience.
Beyond React: 7 Ways of Integrating React With Other Technologies
PUBLISHED 3 DAYS AGO
One of React’s strengths is how well it plays with others. Discover some of the best tools to integrate with the framework.
Readers like you help support MUO. When you make a purchase using links on our site, we may earn an affiliate commission. Read More.
React is a well-known JavaScript library that you can use to make UIs for versatile web applications. React is adaptable and you can combine it with other technologies to make more powerful and effective apps.
Learn how to integrate React with various technologies and you’ll gain benefits from multiple sources.
1. React + Redux
Redux is a state management library used in conjunction with React. Redux facilitates centralized application state management. When building complex applications with many states, React and Redux work well together.
MAKEUSEOF VIDEO OF THE DAY
Here’s an illustration of how to use Redux with React:
import React from 'react';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
const initialState = { count: 0 };
function reducer(state = initialState, action) {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
}
const import React from 'react';
import { useQuery, gql } from '@apollo/client';
const GET_USERS = gql`
query GetUsers {
users {
id
name
}
}
;
function Users() {
const { loading, error, data } = useQuery(GET_USERS);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error :(</p>;
return (
store = createStore(reducer);
function Counter() {
const count = useSelector(state => state.count);
const dispatch = useDispatch();
return (
<div>
<p>Count: {count}</p>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>
<button onClick={() => dispatch({ type: 'DECREMENT' })}>-</button>
</div>
);
}
function App() {
return (
<Provider store={store}>
<Counter />
</Provider>
);
}
export default App;
This example creates a Redux store with an initial state of 0. A reducer function then handles the INCREMENT and DECREMENT operations. The code uses the useSelector and useDispatch hooks to get the ongoing count and dispatch the activities individually.
Finally, to make the store accessible to the entire application, wrap the counter component in the provider component.
2. Server-Side Rendering With Next.js
Next.js is a development framework that optimizes website speed and SEO tactics by transmitting HTML to clients and using server-side rendering of React components.
Its powerful toolset works alongside React, providing exceptional performance and high search engine rankings.
// pages/index.js
import React from 'react';
function Home() {
return (
<div>
<h1>Hello, World!</h1>
<p>This is a server-rendered React component.</p>
</div>
);
}
export default Home;
In this model, you characterize a React component called Home. Next.js makes a static HTML page with the content of this component when it renders it on the server. When the page receives a visit from the client, it will send the HTML to the client and hydrate the component, enabling it to function as a dynamic React component.
3. Data Fetching With GraphQL
GraphQL is a query language for APIs that offers a proficient, strong, and adaptable alternative to REST. With GraphQL, you can get data faster and update the user interface more quickly.
This is an illustration of the way to use GraphQL with React:
import React from 'react';
import { useQuery, gql } from '@apollo/client';
const GET_USERS = gql`
query GetUsers {
users {
id
name
}
}
;
function Users() {
const { loading, error, data } = useQuery(GET_USERS);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error :(</p>;
return (
<ul>
{data.users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
function App() {
return (
<div>
<h1>Users</h1>
<Users />
</div>
);
}
export default App;
This model calls the useQuery function from the @apollo/client library to bring the rundown of clients from the GraphQL Programming interface. The user list is then displayed in the UI.
4. Styling With CSS-in-JS
CSS-in-JS is a JavaScript-based method for styling React components. It makes it simpler to manage complex stylesheets and lets you write styles in a modular and component-based style.
Here’s an illustration of how to use CSS-in-JS with React:
import React from 'react';
import styled from 'styled-components';
const Button = styled.button`
background-color: #007bff;
color: #fff;
padding: 10px 20px;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
&:hover {
background-color: #0069d9;
}
;
function App() {
return (
<div>
<Button>Click me!</Button>
</div>
);
}
export default App;
This example creates a styled button component using the styled function. It defines the button's experience tone, text tone, cushioning, line sweep, text dimension, and cursor.
A hover state that alters the background color when the user hovers over the button is also defined. The button is finally rendered using a React component.
5. Integrating With D3 for Data Visualization
D3 is a data manipulation and visualization JavaScript library. You can make powerful and interactive data visualizations using React. An illustration of how to use D3 with React is as follows:
import React, { useRef, useEffect } from 'react';
import * as d3 from 'd3';
function BarChart({ data }) {
const ref = useRef();
useEffect(() => {
const svg = d3.select(ref.current);
const width = svg.attr('width');
const height = svg.attr('height');
const x = d3.scaleBand()
.domain(data.map((d) => d.label))
.range([0, width])
.padding(0.5);
const y = d3.scaleLinear()
.domain([0, d3.max(data, (d) => d.value)])
.range([height, 0]);
svg.selectAll('rect')
.data(data)
.enter()
.append('rect')
.attr('x', (d) => x(d.label))
.attr('y', (d) => y(d.value))
.attr('width', x.bandwidth())
.attr('height', (d) => height - y(d.value))
.attr('fill', '#007bff');
}, [data]);
return (
<svg ref={ref} width={400} height={400}>
{/* axes go here */}
</svg>
);
}
export default BarChart;
This code defines a BarChart component that accepts a data prop in the previous code snippet. It calls the useRef hook to make a reference to the SVG component that will use it to draw the outline.
After that, it renders the bars of the chart and defines the scales with the useEffect() hook, which maps the values of the data to the coordinates of the screen.
6. Adding Real-Time Functionality With WebSockets
Implementing WebSockets establishes a fully operational two-way avenue that enables continuous communication between a client and server. They enable React to add continuous usefulness to web applications, for example, discussion boards, live updates, and warnings.
You use WebSockets in the following way with React:
import React, { useState, useEffect } from 'react';
import io from 'socket.io-client';
function ChatRoom() {
const [messages, setMessages] = useState([]);
const [inputValue, setInputValue] = useState('');
const socket = io('http://localhost:3001');
useEffect(() => {
socket.on('message', (message) => {
setMessages([...messages, message]);
});
}, [messages, socket]);
const handleSubmit = (e) => {
e.preventDefault();
socket.emit('message', inputValue);
setInputValue('');
};
return (
<div>
<ul>
{messages.map((message, i) => (
<li key={i}>{message}</li>
))}
</ul>
<form onSubmit={handleSubmit}>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
<button type="submit">Send</button>
</form>
</div>
);
}
export default ChatRoom;
In this example, you define a ChatRoom component that uses the socket.io-client library to connect to a WebSocket server. You can use the useState hook to deal with the rundown of messages and the information esteem.
Upon receiving a new message, the useEffect hook registers a listener to trigger a message event update to the message list. To clear and send an input value for the event message, there exists a handleSubmit function.
Subsequently, both the form with an input field and button as well as the updated message list will show on the screen.
With each form submission, calling upon the handleSubmit function is inevitable. To deliver the message to the server, this method makes use of the socket.
7. Integrating With React Native for Mobile Development
React Local is a system for building local universal applications using React, which connect to promote portable applications for iOS and Android stages.
Using the integration of React Native with React, you can use the component-based design and reusable code of React across mobile and web platforms. This reduces mobile app development cycles and time to market. React Native is a popular framework for developing native mobile apps that makes use of the React library.
Introducing vital programming and libraries, like Node.js, Respond Local CLI, and Xcode or Android Studio, is fundamental for designers dealing with iOS and Android separately. Finally, simple React Native components enable developers to create robust and feature-rich mobile applications for the iOS and Android platforms.
Combine React With Other Technologies
React is a well-liked and effective library for building online apps. React is a great option for creating user interfaces, but it is also used with other technologies to increase its capabilities.
By integrating React with these technologies, developers can create more intricate and advanced apps that offer a better user experience. React and its ecosystem of tools and libraries cover everything necessary to create a basic website or a complex web application.
RELATED TOPICS
ABOUT THE AUTHOR
Robert Pearce • MUO Writer(5 Articles Published)
Robert works as a software developer and a freelancer who enjoys writing guides to help other developers. He has a bachelor's in mathematics and computer science. He loves hiking and exploring the world.
https://www.makeuseof.com/category/programming/)
What Is ReactJS, and What Can It Be Used For?
PUBLISHED AUG 28, 2021
Wondering how to create seamless one-page web applications with reusable code components? ReactJS is your answer.
Readers like you help support MUO. When you make a purchase using links on our site, we may earn an affiliate commission. Read More.
If you want to create fast, dynamic user interfaces for your web applications, then you need to learn how to use ReactJS.
React is a client-side JavaScript library, which means it runs on the client/user’s machine in the browser as opposed to running on a server.
It was created in 2011 by the tech giant, Facebook. The React library is used to build dynamic user interfaces and operates by separating aspects of the user interface into what is known as "components".
MAKEUSEOF VIDEO OF THE DAY
In this tutorial article, you’ll learn everything you need to know about React and its components.
What Is ReactJS?
React (also known as ReactJS) is an open-source JavaScript library, which is often erroneously called a framework. This is because React is a direct competitor of top JavaScript frameworks such as AngularJS and VueJS.
React is a library because it doesn’t have a routing mechanism among other framework-specific features. However, there are tools such as the react-router that can be installed and used with the library to achieve framework functionality.
React is more closely related to frameworks such as Angular/Vue than it is to other libraries in the language such as jQuery.
What Are the Benefits of Using ReactJS?
Many developers use React for a plethora of different reasons; some use it because of its speed and performance, and others use it simply because of its popularity. However, there are three major benefits of using the framework that all developers can appreciate.
- It allows you to build your interface using what is referred to as "reusable components" which have state and data.
- It uses a JavaScript syntax extension (JSX) that allows the user to write dynamic HTML.
- It uses a Virtual Document Object Model (VDOM), which allows the developer to update specific sections of a webpage without having to reload the page.
What Are ReactJS Components?
React treats each section of a user interface as a component. Components have states, methods, and functionality.
They allow a developer to separate a user interface into specific sections, which are easily combined to create complex user interfaces. Therefore, if you want to create a customer manager, one component of the user interface can be dedicated to adding a new customer, while another component of the same user interface can be dedicated to displaying the customer list.
RELATED:An Intro To Web Components And Component-Based Architecture
In its simplest form, a component is a JavaScript class or function. They take input values which are called ‘props’ and return specific aspects of a user interface in the form of React elements. For some developers, defining a component as a function is simpler than defining it as a class; however, using either method achieves the same output in React.
Creating a Component with a Function Example
function Customer() {
return (
<div>
<h3>Paul Wilson</h3>
<ul>
<li>Phone: 222-222-2222</li>
<li>Email: Wilsonp@email.com</li>
<li>Balance: $0.00</li>
</ul>
</div>
);
}
export default Customer;
Creating a Component With a Class Example
import React from 'react';
class Customer extends React.Component {
render() {
return (
<div>
<h3>Paul Wilson</h3>
<ul>
<li>Phone: 222-222-2222</li>
<li>Email: Wilsonp@email.com</li>
<li>Balance: $0.00</li>
</ul>
</div>
);
}
}
export default Customer;
As you can see from the examples above, there’s a lot more happening when you create a component using a class. The first important thing to note is that you have to use the render() function when creating a class component.
As you may know, you can’t return directly from a class; therefore, the render() function helps to accomplish this.
The main reason why a developer might choose to use a class over a function is that a class has a state, but thanks to the introduction of hooks, React functions can now also have a state.
What Is JavaScript Syntax Extension?
The JavaScript syntax extension (JSX) is the React element returned by a component. It's a description of what a specific section/component should look like in the user interface. Its appearance is similar to HTML, but in reality, it's JavaScript.
JSX Example
<div>
<h3>Paul Wilson</h3>
<ul>
<li>Phone: 222-222-2222</li>
<li>Email: Wilsonp@email.com</li>
<li>Balance: $0.00</li>
</ul>
</div>
The JSX example above has been pulled from the customer component. The code appears to be HTML, but it's JSX. Though the differences between the two aren’t very apparent from the example above, there are some clear differences. For example, in HTML you use the class property to group similar elements, but in JSX you use the className property.
What Is the Virtual DOM?
The Virtual Document Object Module (VDOM) is a copy of the real DOM. Generally, when an update is made to the real DOM, the user interface, which is altered, will need to be refreshed to display the changes. However, with a Virtual DOM, the changes to a user interface are instantaneous. The state of the Virtual DOM is then used to update the real DOM in a process known as "reconciliation".
Exploring the React Project Files
When a new React project is created, several different files and folders are automatically generated. One of these folders is labeled public. The public folder contains the only HTML file in the React boilerplate, which is entitled index.html.
The index.html file has a
However, the rendering process takes place in another file—index.js—where the React Application root
file, which is the App.js file is rendered then passed to the index.html file. From the index.html file, you can change the title of your web application; however, every other
adjustment to the React application (including the creation of a new component) is made from another folder—the
src folder. The src folder contains the index.js and the
App.js files.
The App.js file is the root react component and it's responsible for what is initially presented
in your web browser on the first React application launch. The App.js file contains a function
called App that returns JSX. Learn more
about the React boilerplate and how to install the react app here. When creating a component there’re two things you need to know. The first and most important is that the newly
created component will never be displayed in your user interface unless it's imported and utilized in the
App component—the App.js file.
The second thing is that it's common practice to begin every component file name with a capital letter. As stated
above, a component can be created using either a function or a class. However, React is moving away from class
components and is now mainly using functions. The code above creates a new customer component and exports the function so that the customer component can be
imported by the App component. As you can see in the example above, the app component imports the customer component and arranges it in the order
that it should appear in the user interface (which in this case is after the customer manager label). The
App component is then exported, and imported by the index.js file, where it's
rendered and displayed in the DOM.
The important thing to remember about the App component is that there can only be one parent element
(which in the example above is the
The code above displays the content of the index.js file that uses the render function to render the
App component to the DOM using the document.getElementById(‘root’) method in the
code above. This is made possible through the root Id used by the index.html file to present the
following output in your browser:
This article provides you with a comprehensive view of the React library, and how to utilize it to create amazing
user interfaces. With React, your user interfaces will not only perform well and look exactly how you want them to,
but they’ll also be easy to maintain (thanks to components). Now you can create professional user interfaces with the React library. But there’s no need to stop at React. There’s
a range of other tools out there that can be used to supplement your front-end development process. RELATED TOPICS ABOUT THE AUTHOR Kadeisha Kean(85 Articles Published) Kadeisha is a Full-Stack Software Developer and Technical/Technology Writer. She has a Bachelor of Science in
Computing, from the University of Technology in Jamaica. PUBLISHED MAY 31, 2019 Ready to start developing websites? These online tools for new and expert web developers are guaranteed to boost your
skills! Readers like you help support MUO. When you make a purchase using links on our site, we may earn an affiliate
commission. Read More. Becoming a web developer is a process. Whether you are taking your first steps into code, or already know how to
program but are moving into online browser-based applications, there is a lot to take in. Luckily for anyone wanting to start, there are many great tools which can help you. Today you'll discover 10 of
the best! A good code editor is essential for developing web apps. Sublime Text used to rule the roost in terms of lightweight
feature-rich text editors for coding. Slowly, developers seem to be moving to Microsoft's open source Visual
Studio Code hybrid code editor. MAKEUSEOF VIDEO OF THE DAY It's easy to see why, with a vast array of
extensions to help all kinds of development, and a built-in collaborative coding Live Share feature.
Code completion, linting, and an integrated terminal make VS Code the only thing you need for developing apps,
websites, and software. If you are learning to develop for the web, you should be using Chrome Developer Tools. Available free with the
Google Chrome browser, they give robust inspection and debugging on all websites. Highlighting page elements in code and vice versa allows you to get a good sense of how websites come together. There
is also a built-in device emulator for testing how websites work on a variety of devices. Powerful site metrics and
security checking make Chrome Developer Tools essential for all web devs. For a simple but effective way to work out custom grid sizes, GridGuide can help. Its simple user interface allows
you to specify width, columns, and outer gutter ratio. It returns examples of what different sized grid settings will look like along with the pixel values required to
replicate it in your visual design. Grids are shareable and available as PNG files for later reference. CodePen is an online social development environment for designing and sharing front end development. Focusing purely
on the various flavors of HTML, CSS, and JavaScript, the standard CodePen window is the perfect place to experiment
and share your ideas. Frequent community showcases and challenges are open to developers at all levels, and examples of almost anything
you'd want to make in the browser are available to view, or fork for your own use. JavaScript is the language of the internet, and JavaScript Object Notation (JSON) is the primary way to manipulate
data online. While other tools can help create JSON from code, being able to generate it on the fly is vital for
testing and development. ObjGen takes input in the left window and converts it into JSON in the right window, which saves in the browser, or a
JSON file for later use. Perfect for anyone learning data visualization and full stack web development. Getting the color scheme right for your website is an essential part of any design. You'll find many apps online
which allow you to generate and build color palettes for free. Coolers is an example of a simple to use app which
helps you settle on your visual feel. The space bar generates a new color palette as a starting point. Each color comes with alternatives and tweaking
tools to get it just right. When you are happy with a color, you can lock it and generate new colors based on it.
Available for free in the browser (and available as an iOS app) it's an excellent tool for all frontend
designers. This browser-based API documentation browser is free and gives programmers a quick place to reference multiple
codebases using a simple web UI. All major languages are supported, and any that you choose are searchable, available offline in the browser, as a
plugin to VS Code and Sublime Text, and on mobile. DevDocs is a game changer, giving quick access to documentation for your project. A not-so-secret about web development: CSS sucks. Luckily there are options out there to make styling your websites
easier. Syntactically Awesome Style Sheets (Sass) is a CSS extension language for quick and easy website structure.
Completely compatible with already available CSS libraries, various frameworks are also available to kick start your
design. Inheritance, Mixins, and Operators are all supported in Sass, making it a powerful tool for browser-based
projects. Frontend frameworks come and go, but currently, ReactJS is dominating web development. Designed by Facebook and a
community of developers under the MIT license, it is the most popular single-page app tool and can fit into any web
application. Powerful data binding, a virtual Document Object Model (DOM), and hooks allow for complete control over code
execution and performance. ReactJS uses JavaScript XML (JSX) allowing developers to mix HTML and JavaScript elements
easily. ReactJS looks good on any web development CV; job postings for ReactJS developers show no signs of slowing down! Having a site that loads quickly is essential. No matter how well you design your user experience, slow running web
pages are an immediate turnoff. Chrome Developer Tools can give you metrics for your site. Sometimes, however,
it's nice to get an outside impression of how your website performs. Pingdom provides a service to test the speed of your website and gives various metrics to help you debug what might
be slowing you down. The test grades each element for performance and advises what you can improve on. Pingdom has a
limited free service, with paid models available on a sliding scale. Having the right tools to hand makes any job more manageable. When that job is learning web development,
then it can improve your overall experience. All the tools in the world can't replace experience and practice. The best way to improve is to pick some beginner programming projects to get you
started. RELATED TOPICS ABOUT THE AUTHOR Ian Buckley(227 Articles Published) Ian Buckley is a freelance journalist, musician, performer and video producer living in Berlin, Germany. When
he's not writing or on stage, he's tinkering with DIY electronics or code in the hope of becoming a mad
scientist.Creating a Component
Creating a New Component Example
function Customer() {
return (
<div>
<h3>Paul Wilson</h3>
<ul>
<li>Phone: 222-222-2222</li>
<li>Email: Wilsonp@email.com</li>
<li>Balance: $0.00</li>
</ul>
</div>
);
}
export default Customer;
Using the App Component Example
import Customer from './components/Customer';
function App() {
return (
<div>
<h1>Customer Manager</h1>
<Customer/>
</div>
);
}
export default App;
Rendering the App Component Example
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
Now You Can Create Components in ReactJS
Upgrade Your Web Development Skills With
These 10 Essential Tools
1. Visual Studio Code
2. Chrome Developer
Tools
3. GridGuide
4. CodePen
5. ObjGen
6. Coolors
7. DevDocs
8. Sass
9. ReactJS
10. Pingdom
The Right Tools for the Job