React JS is an open-source JavaScript library that has revolutionized the way web developers create and build single-page applications. It is used by some of the biggest companies in the world, including Facebook, Instagram, Netflix, and Airbnb. If you’re passionate about web development and are looking to add new skills to your resume, then learning React JS will be crucial.
This React JS tutorial is perfect for web developers who are just starting with front-end web development and need to learn the basics of React. In this tutorial, we will go through the process of setting up a development environment, the basics of React components, using state, props, event handling, and conditional rendering.
Setting up the Development Environment
Before we can start writing any code, we need to set up our development environment. The following steps will guide you on how to do that:
- Installing Node.js and NPM
The first step to setting up your environment is to install Node.js and NPM (Node Package Manager). Node.js is a JavaScript runtime environment that allows developers to run JavaScript code outside the browser. Meanwhile, NPM is a package manager that is used to install third-party libraries and packages.
To install Node.js, visit https://nodejs.org/en/download/ website and download the version that is compatible with your operating system. Once downloaded, run the installation file and follow the prompts on the screen.
- Installing the React JS library
Once Node.js and NPM are installed, the next step is to install the React JS library. To do that, open your command prompt and run the following command:
npm install -g create-react-app
This command will install the create-react-app CLI tool globally. This tool enables you to create new React projects quickly. After the installation is complete, navigate to the directory where you would like your project to live and run the following command:
create-react-app my-react-app
This command will create a new React project in a directory called my-react-app.
- Creating a new React project using Create React App tool
Finally, navigate to your project directory and start the React development server using the following command:
cd my-react-app && npm start
Congratulations, you now have a working React development environment. Now it’s time to start coding.
The Basics of React JS
React JS uses a component-based architecture, which makes it easy to break up your user interface into reusable pieces of code. Before we dive deep into creating components, let’s first understand what they are.
Understanding React Components
A React component is a reusable piece of HTML code that encapsulates some data and functionality. It is intended to be modular and reusable across different parts of your application. Every React application has at least one React component, which is known as the root component.
There are two ways to define components in React, the functional and class-based approach.
Creating Components Using a Functional and Class-Based Approach
Functional components are JavaScript functions that accept props (short for properties) and return a React element. Props are properties that can be passed down to a component from its parent component. The following code is an example of how to create a basic functional component in React.
function Greetings(props) {
return (
<div>
<h1>Hello, {props.name}!</h1>
</div>
);
}
The above component takes a single prop called name and displays “Hello, name!” in the browser. Props are passed as key-value pairs in a JavaScript object. For example, if you wanted to render the Greetings component with the name “John”, you would pass the following prop:
<Greetings name="John" />
Class-based components are similar to functional components, but they are declared using ES6 classes. They offer more features and are more powerful than functional components. Here’s an example of a class-based component in React:
import React, { Component } from 'react';
class Button extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log("Button clicked");
}
render() {
return (
<button onClick={this.handleClick}>
Click Me
</button>
);
}
}
export default Button;
The above class-based component is called Button. It has a constructor that accepts props, a handleClick method that logs a message to the console when the button is clicked, and a render method that returns a button element with an onClick event listener attached to it.
Rendering Components in the DOM
The final step in creating a React component is to render it in the browser. To do this, we use the ReactDOM library, which is a part of React. Here’s an example of how to render a component in the browser:
import React from 'react';
import ReactDOM from 'react-dom';
import Greetings from './Greetings';
ReactDOM.render(
<Greetings name="John" />,
document.getElementById('root')
);
The code above uses the ReactDOM.render() method to render the Greetings component to the element with an ID of root in the index.html file.
State and Props
In React, there are two types of data that we deal with, state and props. Understanding the difference between state
and props is crucial when building React applications.
Understanding State and Props in React
Props are properties passed into a component from its parent component. They are read-only and cannot be modified by the component they are passed to. State, on the other hand, is local data that is used within a component that can be changed by that component.
Passing Data Between Components Using Props
Props are used to pass data from a parent component to a child component. This is achieved by passing data through the child component’s props. Here’s an example of a parent component passing down a prop to a child component:
import React from 'react';
import ChildComponent from './ChildComponent';
class ParentComponent extends React.Component {
render() {
return (
<div>
<ChildComponent myProp="Hello, World!" />
</div>
);
}
}
export default ParentComponent;
The code above creates a ParentComponent that renders a ChildComponent and passes down a prop called myProp as a string.
Updating a Component’s State Using setState()
A component’s state can only be updated using the setState() method provided by React. Here’s an example:
import React from 'react';
class ExampleComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 0
};
}
handleIncrement = () => {
this.setState({
counter: this.state.counter + 1
});
};
render() {
return (
<div>
<p>{this.state.counter}</p>
<button onClick={this.handleIncrement}>Increment</button>
</div>
);
}
}
export default ExampleComponent;
The code above creates an ExampleComponent with a state property called counter, which is initialized to 0 in the constructor. The component has a handleIncrement method that is executed when the button is clicked, which increments the counter value by 1 using the setState() method.
Handling User Events
React provides an easy way to handle user events within components using event handlers. Here’s an example of how to create an event handler for a button element using React:
import React from 'react';
class Button extends React.Component {
handleClick = () => {
alert('Button clicked');
}
render() {
return (
<button onClick={this.handleClick}>Click Me</button>
);
}
}
export default Button;
The above code creates a button element with an onClick event handler that triggers an alert when clicked.
Conditional Rendering and CSS Styling
React allows you to conditionally render components based on different conditions. Here’s an example:
import React from 'react';
class ExampleComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoggedIn: false,
};
}
render() {
const isLoggedIn = this.state.isLoggedIn;
if (isLoggedIn) {
return <h1>Welcome back!</h1>;
}
return <h1>Please log in</h1>;
}
}
export default ExampleComponent;
The code above creates an ExampleComponent that conditionally renders the text “Welcome back!” or “Please log in” based on the value of isLoggedIn. If isLoggedIn is true, it will render the first statement; otherwise, it will render the second statement.
You can also style your React components using CSS. Here’s an example of how to do that:
import React from 'react';
import './Button.css';
class Button extends React.Component {
render() {
return (
<button className="custom-button">
Click Me
</button>
);
}
}
export default Button;
The code above creates a Button element that uses an external CSS file called Button.css to style the button with a custom class called “custom-button”.
React Router
React Router is a powerful library for managing routes in a React application. It allows you to navigate between different pages of your application without the need for reloading the page. Here’s an example of how to use React Router in a React application:
import React from 'react';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import HomePage from './HomePage';
import AboutPage from './AboutPage';
import ContactPage from './ContactPage';
const App = () => {
return (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
</ul>
</nav>
<Switch>
<Route path="/about">
<AboutPage />
</Route>
<Route path="/contact">
<ContactPage />
</Route>
<Route path="/">
<HomePage />
</Route>
</Switch>
</div>
</Router>
);
};
export default App;
The code above creates a React application with three pages: HomePage, AboutPage, and ContactPage. The app uses React Router to manage the different routes and renders the relevant
component when the route changes. The Link component is used to create navigation links within the application.
Conclusion
React JS is a powerful tool that can help you build complex and dynamic single-page applications. In this tutorial, we covered the basics of React development, including setting up the development environment, creating components using both functional and class-based approaches, using state and props, handling user events, and conditional rendering and styling with CSS.
We also covered the use of React Router to manage navigation within a React application. With this knowledge, you can start building your own React applications and dive deeper into the world of front-end web development. Remember that practice makes perfect, so keep coding and experimenting with React to become a better developer.
Happy coding!
Routing In React JS Using React Router
Introduction React JS has become one of the most popular frontend frameworks for web development. It allows developers to create complex and dynamic user interfaces with ease. Routing is an essential part of web development, and React Router is one such library that is used to manage routing in React applications. In this article, we’ll […]
React JS Interview Questions (and answers)
Introduction: React is a powerful JavaScript library with a growing presence in web development today. With its powerful rendering capabilities and cross-functional library, it has become an important skill for developers to learn. In order to prepare for React interviews, it is important to familiarize yourself with React interview questions, which cover a range of […]
React Charts With ChartJS 2
As a web developer, I understand the importance of data visualization in presenting complex information in an understandable and visually appealing way. That’s why I’ve been using ChartJS 2, a powerful JavaScript library, for creating charts in my React apps. In this article, I’ll show you how to set up and use ChartJS 2 in […]
What Is JSX and how to use it.
Introduction As a web developer, I’m always on the lookout for new tools and technologies that can help me write better code faster. One tool that has caught my attention lately is Typescript JSX. In this article, I’m going to share my experience learning Typescript JSX and the benefits it has brought to my development […]
React JS vs Vue: A Comprehensive Guide
Introduction ReactJS and Vue are two of the most popular JavaScript libraries used to develop dynamic user interfaces. These libraries have gained widespread popularity due to their flexibility, efficiency, and ease of use. ReactJS was developed by Facebook, and Vue was created by Evan You. In this article, we are going to evaluate and compare […]
Create Forms In React Using React Hook Form
Introduction React Hook Form is a popular tool used in building forms in React.js. It is a performant library that simplifies the process of building forms by reducing boilerplate code and providing convenient features. This article is aimed at introducing the basic concepts of React Hook Form and how to use it to create forms […]