React JS tutorial

React js tutorial in 45 minutes

Master the basics of programming with our tutorial The Building Blocks of Computer Programming Beginner-friendly with essential concepts with clear explanation.

Concepts:

1. React Introduction

2. Prerequisites

3. Installation

4. Environment Set Up

5. First React Application

6. React Components

7. React JSX

8. React Props

9. React State

10. React Life Cycle

11. React Events

12. React Forms

13. React Conditional Rendering

14. React Lists and Keys

15. React Higher-Order functions

16. React Asynchronus Programming

17. React Networking

18. React Persistence

19. React Animations

20. React Testing

1. React JS Introduction

React is a popular JavaScript library for building user interfaces. It was developed by Facebook, and is often used for building single-page applications and mobile applications.

One of the main features of React is the way it allows you to define your application's UI as a function of its state. This means that you can describe the structure and content of your UI using declarative components, and React will automatically update the UI when the underlying data changes.

React uses a virtual DOM (a lightweight in-memory representation of the actual DOM) to improve performance by minimizing the number of DOM updates that are needed when the UI is updated. This makes it an efficient choice for building large, complex applications that may need to update the UI frequently.

2. Prerequisites

To start learning React, you should have a basic understanding of JavaScript and the web. Here are some specific things you should be familiar with before diving into React

1. HTML and CSS: React is a JavaScript library, so you'll need to know how to create and style web pages using HTML and CSS.

2. JavaScript: React is written in JavaScript, so you'll need to be comfortable with the language to use it effectively. This includes concepts like variables, functions, asynchronus programming, objects and all other ES6 features.

3. Web development concepts: It's helpful to have a basic understanding of how the web works, including concepts like HTTP, servers, and the DOM.

4. A text editor: You'll need a text editor to write your code. Some popular options include Visual Studio Code, Sublime Text, and Atom.

5. A modern web browser: You'll need a web browser to test your React applications. Some popular options include Google Chrome, Mozilla Firefox, and Safari.

While it's not required, it can also be helpful to have some experience with a JavaScript build tool like webpack or Babel. These tools are often used to compile and bundle React code for production use.

3. Installation

There are a few different ways to install React, depending on your needs. Here are the steps for installing React using a package manager like npm or yarn

1. Install Node.js

React is built with JavaScript, and you'll need Node.js installed on your computer to use React. You can download the latest version of Node.js from the official website https://nodejs.org/ or through a package manager like Homebrew (for macOS).

2. Create a new project directory

Create a new directory on your computer where you want to store your React project. This will be the root of your project.

3. Initialize the project

Open a terminal window and navigate to the root of your project directory. Then, run the following command to initialize the project:

npm init -y

This will create a 'package.json' file in your project directory, which stores information about your project, including the dependencies it requires.

4. Install React

Next, you'll need to install React itself. Run the following command to install React and save it as a dependency in your package.json file

npm install react react-dom --save

4. Environment Set Up

To set up a development environment for React, you'll need to install a few tools on your computer. Here are the steps to set up a basic React development environment

After you finishing the "Installation" steps you can follow these steps

1. Create the project files

Create the following files in your project directory

1. index.html: This will be the HTML file for your React application.

2. index.js: This will be the entry point for your React application.

3. app.js: This will be the main component for your React application.

2. Add the React libraries

In your 'index.html' file, add the following script tags to include the React and ReactDOM libraries


<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

3. Write some code

In your 'app.js' file, add the following code to create a simple React component


import React from 'react';

function App() {
     return <div>Hello, world!</div>;
}

4. Render the component

In your 'index.js' file, add the following code to render the App component


import React from 'react';
import ReactDOM from 'react-dom';

import App from './app';

ReactDOM.render(<App />, document.getElementById('root'));


5. Run the project

Open your 'index.html' file in a web browser to see your React application in action.

5. First React Application

Let's build a simple "Hello, World!" application in React

As said above, To create a "Hello, World!" application in React, you will need to have Node.js and npm (the Node.js package manager) installed on your computer.

Here's one way you can create a "Hello, World!" application in React:

1. Create a new directory for your project, and navigate to it in the terminal.

2. Run the following command to create a new React app

npx create-react-app hello-world

This will create a new directory called "hello-world" with the necessary files for a React app.

3. Navigate to the "hello-world" directory and start the development server by running the following command:


cd hello-world
npm start
     

This will open a new browser window with the "Hello, World!" app running.

4. Open the file 'src/App.js' in a text editor. This is the root component of your React app. Replace the contents of the file with the following code


import React from 'react';

function App() {
     return <h1>Hello, World!</h1>;
}

export default App;
     

5. Save the file and the browser window will automatically refresh with the updated "Hello, World!" message.

Successfully, we created a simple "Hello, World!" application in React

6. React Components

In React, a component is a piece of reusable code that represents a part of a user interface. Components allow you to split your UI into smaller, reusable pieces, which makes it easier to build and maintain complex applications.

There are two types of components in React: functional components and class components.

Functional components are simple JavaScript functions that accept props (short for properties) as an argument and return a React element. They are often used for presenting static data, or for simple logic that doesn't require state.


import React from 'react';

function HelloMessage(props) {
     return <div>Hello {props.name}</div>;
}
     

Class components, on the other hand, are JavaScript classes that extend the 'React.Component' class. They can have state, lifecycle methods, and other features that are not available to functional components.


import React from 'react';

class HelloMessage extends React.Component {
render() {
  return <div>Hello {this.props.name}</div>;
}
}
     

To use a component in your application, you can simply import it and render it like any other element. For example

     
import React from 'react';
import ReactDOM from 'react-dom';

import HelloMessage from './HelloMessage';

ReactDOM.render(
     <HelloMessage name="John" />,
     document.getElementById('root')
);
          
     

example


import React from 'react';
import ReactDOM from 'react-dom';

     function Greeting(props) {
     return <h1>Hello, {props.name}</h1>;
}

     class App extends React.Component {
     render() {
     return (
          <div>
          <Greeting name="John" />
          <Greeting name="Jane" />
          </div>
     );
     }
}

 ReactDOM.render(
     <App />,
     document.getElementById('root')
);

In this example, we define two components: a functional component called Greeting, and a class component called App.

The Greeting component is a simple function that takes a name prop and returns a h1 element with a greeting message.

The 'App' component is a class that comes from React.Component. It has a single method called render, which returns a JSX element that contains two instances of the Greeting component.

Finally, we use the 'ReactDOM.render' function to render the App component to the DOM. This will create a tree of React elements that will be rendered to the page.

When the page loads, you should see two greeting messages: "Hello, John" and "Hello, Jane".

7. React JSX

JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like code in your JavaScript files. It is commonly used in the React JavaScript library for building user interfaces.

In React, JSX is used to define the structure of a component's user interface. It looks like HTML, but it is actually just JavaScript that is syntactically similar to HTML. For example, here is a simple JSX element that renders a div element with the text "Hello, World!"

const element = <div>Hello, World!</div>;

JSX elements can contain other JSX elements, as well as JavaScript expressions.


const name = 'John';
const element = <h1>Hello, {name}!</h1>;

JSX elements must have a single root element, so if you want to return multiple elements from a component, you will need to wrap them in a parent element.


return (
     <div>
     <h1>Hello, World!</h1>
     <p>This is a paragraph</p>
     </div>
);


JSX is not required to use React, but it is a convenient way to define the structure of a component's user interface and make it easier to read and understand.

8. React Props

In React, props (short for "properties") are a way to pass data from a parent component to a child component. Props are, cannot be modified by the child component.

The 'props' object is generally used to access the props for the component. For example, consider the following component that displays a message


function Message(props) {
     return <h1>{props.message}</h1>;
     }
        

To pass a prop to this component, you can use JSX syntax to specify the prop name and value


<Message message="Hello, World!" />

This will render the component with the message "Hello, World!".

Props can be of any type, including numbers, strings, arrays, and even objects. You can also pass functions as props, which can be useful for defining event handlers or for performing other actions in the parent component.

     
import React from 'react';

function Message(props) {
     return (
     <div>
       <h1>{props.title}</h1>
       <p>{props.message}</p>
     </div>
     );
}

function App() {
     return (
     <div>
          <Message title="Hello" message="Welcome to my app" />
          <Message title="Goodbye" message="Thank you for visiting" />
     </div>
     );
}

export default App;

     

In this example, the Message component expects two props: title and message. The App component renders two instances of the Message component, each with its own set of props.

When the component is rendered, the JSX code will be transformed into actual HTML that will be displayed in the browser. The resulting HTML is look like this


<div>
   <div>
     <h1>Hello </h1>
     <p>Welcome to my app </p>
   </div>
<div>
     <h1>Goodbye </h1>
     <p>Thank you for visiting </p>
</div>
</div>
        

This example demonstrates how you can use props to customize the behavior and appearance of a component, without having to write new code for each instance of the component.

9. React State

In React, state is an object that represents the component's internal data. It is used to store and manage the component's data and behavior.

State is considered to be private to a component, and it should only be modified using React's setState() method. This ensures that the component's internal state is consistent with the component's rendered output, and helps to prevent unexpected behavior.

To use state in a React component, you need to define a class component by extending the 'React.Component' class and adding a 'constructor' method to initialize the component's state. Here's an example of a simple component that displays a message


import React from 'react';

class Message extends React.Component {
     constructor(props) {
     super(props);
     this.state = {
          message: 'Hello, World!'
     };
     }

     render() {
     return <h1>{this.state.message}</h1>;
     }
}

To access the component's state, you can use the 'this.state' object. To update the state, you can use the 'setState()' method, which will trigger a re-render of the component.

Here's an example of a component that allows the user to toggle between two different messages


import React from 'react';

class ToggleMessage extends React.Component {
constructor(props) {
super(props);
this.state = {
     showMessage: true
};
}

toggleMessage = () => {
this.setState(prevState => ({
     showMessage: !prevState.showMessage
}));
}

render() {
return (
     <div>
     {this.state.showMessage && <p>Hello, World!</p>}
     <button onClick={this.toggleMessage}>Toggle Message</button>
     </div>
);
}
}
     

In this example, the 'ToggleMessage' component has a state with a single boolean property called 'showMessage'. When the button is clicked, the 'toggleMessage' function is called, which toggles the value of 'showMessage' and updates the component's state using 'setState()'. This causes the component to re-render, and the message is displayed or hidden based on the value of 'showMessage'.

10. React Life Cycle

React components have a lifecycle of events that occurs from the time the component is created to the time it is destroyed. These events are called lifecycle methods, and they allow you to control the behavior of a component at different stages of its lifecycle.

There are several lifecycle methods in React, and they can be grouped into three categories

1. Mounting

These methods are called when a component is being inserted into the DOM.

constructor(): This method will call before the component is mounted. It is used to initialize state and bind event handlers.

render(): This method is called to render the component's JSX.

componentDidMount(): This method is called after the component has been rendered and added to the DOM. It is often used to trigger API calls or perform other side effects.

2. Updating

These methods are called when a component's state or props are changed.

shouldComponentUpdate(): This method is called before the component is re-rendered due to a state or prop change. It can be used to optimize performance by avoiding unnecessary re-renders.

render(): This method is called to re-render the component.

getSnapshotBeforeUpdate(): This method is called before the component's updated DOM is committed. It can be used to capture information from the DOM that may be lost during the update.

componentDidUpdate(): This method is called after the component's updated DOM has been committed. It is often used to trigger API calls or perform other side effects.

3. Unmounting

This method will call when the component is being removed from the DOM.

componentWillUnmount(): This method will call before the component is unmounted and destroyed. It is often used to perform cleanup tasks such as canceling network requests or removing event listeners.

By implementing these lifecycle methods, you can control the behavior of your components at different stages of their lifecycle and perform actions such as fetching data, setting up event listeners, and cleaning up resources.

11. React Events

In React, events are triggered by user actions, such as clicking a button, typing in a text field, or hovering over an element. You can attach event handlers to your React components to specify the behavior that should occur when an event is triggered.

To handle an event in a React component, you can use the 'on' prefix followed by the event name, and assign a function to the event handler. For example, to handle a click event on a button, you can use the 'onClick' event handler


import React from 'react';

function Button() {
     const handleClick = () => {
     console.log('Button was clicked');
     };

     return <button onClick={handleClick}>Click me</button>;
}

In this example, the 'handleClick' function is called whenever the button is clicked. You can also pass arguments to the event handler function, if needed. For example


import React from 'react';

function ListItem(props) {
     const handleClick = index => {
     console.log(`List item ${index} was clicked`);
     };

     return <li onClick={() => handleClick(props.index)}>{props.item}</li>;
}

function List(props) {
     const items = ['item 1', 'item 2', 'item 3'];
     return (
          <ul>
          {items.map((item, index) => (
               <ListItem key={item} item={item} index={index} />
          ))}
          </ul>
     );
}
     

In this example, the 'ListItem' component has an 'onClick' event handler that calls the 'handleClick' function with the index prop as an argument. When a list item is clicked, the 'handleClick' function will be called with the index of the item that was clicked.

React supports a wide range of events, including mouse events, keyboard events, and touch events.

12. React Forms

In React, forms are used to collect user input and allow users to interact with your application. Forms are created using a combination of HTML form elements and React components.

To create a 'form' in React, you can use the form element and the 'input', 'select', and 'textarea' elements to create the form fields. Here's an example of a simple form that allows the user to enter their name and email address


import React from 'react';

class ContactForm extends React.Component {
     constructor(props) {
     super(props);
     this.state = {
          name: '',
          email: ''
     };
     }

     handleChange = event => {
     this.setState({
          [event.target.name]: event.target.value
     });
     }

     handleSubmit = event => {
     event.preventDefault();
     console.log(this.state);
     }

     render() {
     return (
          <form onSubmit={this.handleSubmit}>
               <labe>
          Name:
          <input
               type="text"
               name="name"
               value={this.state.name}
               onChange={this.handleChange}
          />
          </label>
          <<br />
          <label>
          Email:
          <input
               type="email"
               name="email"
               value={this.state.email}
               onChange={this.handleChange}
          />
          </label>
          <br />
          <button type="submit">Submit</button>
          </form>
     );
     }
}
     

In this example, the 'ContactForm' component has a state with two properties: 'name' and 'email'. The 'handleChange' function is called whenever the user types in the form fields, and it updates the corresponding state property with the new value. The 'handleSubmit' function is called when the form is submitted, and it prevents the default form submission behavior and logs the form data to the console.

React also provides a number of form-related components, such as Form, Label, and Input, that can be used to build more complex forms with additional functionality.

13. React Conditional Rendering

In React, you can use conditional rendering to render different elements or components based on a condition. This is useful for rendering different content based on the state of your application or for rendering different components depending on the user's input or interaction with your app.

To perform conditional rendering in React, you can use JavaScript's 'if' and 'ternary' operators, or the '&&' operator.

Here's an example of how you can use the if operator to render different elements based on a condition


import React from 'react';

function UserInfo(props) {
     if (props.user) {
     return (
          <div>
          <p>Name: {props.user.name}</p>
          <p>Email: {props.user.email}</p>
          </div>
     );
     } else {
     return <p>Loading...</p>;
     }
}


This example will only render the user's name and email if the user prop is truthy. If the user prop is null or undefined, the component will not render anything.

Conditional rendering is a powerful tool for building flexible and dynamic user interfaces in React.

14. React Lists and Keys

In React, lists are used to render a collection of items, such as a list of users, a list of products, or a list of comments. To create a list in React, you can use the 'map()' function to iterate over the collection and return an array of elements.

Here's an example of how you can create a list of users


import React from 'react';

function UserList(props) {
     const users = [
     { id: 1, name: 'John' },
     { id: 2, name: 'Jane' },
     { id: 3, name: 'Bob' }
     ];

     return (
     <ul>
          {users.map(user => (
               <li key={user.id}>{user.name}</li>
          ))}
          </ul>
     );
}
     

In this example, the 'UserList' component iterates over the 'users' array and creates a list item for each user.

It's important to note that when you create a list in React, you should include a unique 'key' prop for each item in the list. The 'key' prop is used by React to identify each element in the list and ensure that the elements are rendered correctly. The 'key' prop should be a unique value that identifies each element, such as an ID or index.

Here is an example of using the index of each element as the key prop in a React component


import React from 'react';

function MyList(props) {
     const items = ['item1', 'item2', 'item3'];

     return (
          <ul>
          {items.map((item, index) => (
               <li key={index}>{item}</li>
          ))}
     </ul>
     )
}

export default MyList;
     

In this example, we have an array of strings called items that we want to render as a list. We use the map method to iterate over the array and return a list item element for each element in the array. We pass the index of each element as the key prop for each list item element.

This is useful when the elements in the array do not have unique identifying properties and you need a way to distinguish between them. The key prop is used by React to keep track of each element in the list, so it is important to use a unique value for the key prop of each element.

15. React Higher-Order functions

In React, a higher-order function is a function that takes a component as an argument and returns a new component. These functions are often used to abstract common behavior that can be shared among multiple components.

Here is an example of a higher-order function that takes a component and adds a new prop called 'title' to it


import React from 'react';

function withTitle(WrappedComponent) {
     return class extends React.Component {
     render() {
          return <WrappedComponent {...this.props} title="My Title" />;
     }
     }
}
     

This higher-order function can be used to wrap any component and add a title prop to it. For example


import React from 'react';
import MyComponent from './MyComponent';
import withTitle from './withTitle';

const MyComponentWithTitle = withTitle(MyComponent);

function App() {
     return (
     <MyComponentWithTitle />
     );
}
     

In this example, 'MyComponentWithTitle' is a new component that has all the props of 'MyComponent', plus a new prop called 'title'.

16. React Asynchronus Programming

Asynchronous programming is a way of writing code that can perform tasks concurrently, rather than in a blocking, sequential manner. This is important in React because it allows you to perform long-running or network operations without freezing the UI or blocking other user interactions.

There are several ways to perform asynchronous tasks in React, including using async/await, Promises, and the 'useEffect' hook.

Here is an example of using async/await to perform an asynchronous operation in a React component


     import React, { useState, useEffect } from 'react';

     async function fetchData() {
       const response = await fetch('https://api.example.com/data');
       const data = await response.json();
       return data;
     }
     
     function MyComponent() {
       const [data, setData] = useState(null);
     
       useEffect(() => {
         async function getData() {
           const data = await fetchData();
           setData(data);
         }
         getData();
       }, []);
     
       return (
          <div>
           {data ? <p>{data.message}</p> : <p>Loading...</p>}
         </div>
       );
     }
     
     export default MyComponent;
     

In this example, we use the useEffect hook to perform an 'async' operation when the component mounts. The 'fetchData' function uses the 'await' keyword to wait for the promise returned by 'fetch' to resolve, and then parses the response as JSON. The component displays a loading message while the data is being fetched, and then displays the data when it becomes available.

17. React Networking

In React, networking refers to the process of making network requests (e.g., HTTP requests) to retrieve or send data from a server. Networking is a common task in web development, and there are many ways to perform networking in React.

One way to perform networking in React is by using the fetch API. Here is an example of using fetch to retrieve data from a server in a React component


import React, { useState, useEffect } from 'react';

function MyComponent() {
     const [data, setData] = useState(null);

     useEffect(() =>{
     async function getData() {
          const response = await fetch('https://api.example.com/data');
          const data = await response.json();
          setData(data);
     }
     getData();
     }, []);

     return (
     <div>
          {data ? <p>{data.message}</p> : <p>Loading...</p>}
          </div>
     );
}

export default MyComponent;
     

In this example, we use the useEffect hook to perform a network request when the component mounts. The fetch function makes an HTTP GET request to the specified URL and returns a promise that resolves with a Response object. We then call the json method on the Response object to parse the response as JSON.

There are many other ways to perform networking in React, including using libraries like Axios or the XMLHttpRequest API. You can also use the useReducer hook and the Redux library to manage network requests and data in a more scalable way.

18. React Persistence

In React, persistence refers to the ability to store and retrieve data in a way that persists beyond a single session or page refresh. There are several ways to add persistence to a React app, including using cookies, local storage, and server-side storage.

Here is an example of using local storage to persist data in a React component


import React, { useState } from 'react';

function MyComponent() {
     const [message, setMessage] = useState('');

     useEffect(() => {
     const storedMessage = localStorage.getItem('message');
     if (storedMessage) {
          setMessage(storedMessage);
     }
     }, []);

     function handleChange(event) {
     setMessage(event.target.value);
     localStorage.setItem('message', event.target.value);
     }

     return (
     <div>
        <input value={message} onChange={handleChange} />
     </div>
     );
}

export default MyComponent;
     

In this example, we use the useEffect hook to check for a stored value in local storage when the component mounts. If a value is found, we use the setMessage function to update the component's state. We also use the handleChange function to update the state and store the new value in local storage whenever the user types in the input field.

Local storage is a simple and convenient way to add persistence to a React app, but it has some limitations. The stored data is only available on the same device and browser, and it is vulnerable to data loss if the user clears their browser cache.

Other options for adding persistence to a React app include using cookies or server-side storage solutions like a database or cloud storage.

19. React Animations

In React, animations refer to the process of creating visual transitions between elements on the screen. Animations can be used to add visual interest and polish to a React app, and there are many ways to implement animations in React.

One way to implement animations in React is by using the animate.css library and the react-animations library. Here is an example of using these libraries to add a fade-in animation to a React component


import React from 'react';
import { FadeIn } from 'react-animations';
import 'animate.css/animate.css';
import './MyComponent.css';

function MyComponent() {
return (
<div className="animated fadeIn">
   <p>I will fade in!</p>
</div>
);
}

export default MyComponent;
     

In this example, we import the FadeIn animation from the react-animations library and the animate.css styles. We then apply the fadeIn class to the component's root element, which will trigger the fade-in animation when the component mounts.

Another way to implement animations in React is by using the react-spring library, which provides a powerful and flexible way to create spring-based animations. Here is an example of using react-spring to animate a component's position


import React, { useState, useEffect } from 'react';
import { useSpring, animated } from 'react-spring';

function MyComponent() {
     const [isOpen, setIsOpen] = useState(false);
     const springProps = useSpring({
     transform: isOpen ? 'translate3d(0,0,0)' : 'translate3d(0,-100%,0)',
     });

     return (
     <animated.div style={springProps}>
        <button onClick={() => setIsOpen(!isOpen)}>Toggle</button>
        <p>I will animate!</p>
        </animated.div>
     );
}

export default MyComponent;
     

In this example, we use the useSpring hook to create a spring-based animation that updates the component's transform style based on the value of the isOpen state variable. When the isOpen variable is true, the component will be visible on the screen, and when it is false, the component will be hidden off the screen.

There are many other ways to implement animations in React, including using CSS transitions, the react-transition-group library, and the React Native animation APIs.

20. React Testing

Testing is an important part of the development process in React, as it allows you to ensure that your code is working correctly and as expected. There are many tools and libraries available for testing React components, including Jest, Enzyme, and React Testing Library.

Here is an example of a test for a simple React component using Jest and Enzyme


import React from 'react';
import { shallow } from 'enzyme';
import MyComponent from './MyComponent';

describe('MyComponent', () => {
     it('renders the component', () => {
     const wrapper = shallow(<MyComponent />);
     expect(wrapper).toMatchSnapshot();
     });

     it('updates the state when the button is clicked', () => {
     const wrapper = shallow(<MyComponent />);
     wrapper.find('button').simulate('click');
     expect(wrapper.state('isClicked')).toBe(true);
     });
});
     

In this example, we use Jest to define a test suite for the MyComponent component. The first test uses Enzyme's shallow function to render the component and create a "wrapper" object that we can use to access the component's properties and methods. We use the toMatchSnapshot function to create a snapshot of the rendered component and ensure that it does not change unexpectedly.

The second test uses Enzyme's find and simulate functions to simulate a click event on the component's button and check that the component's isClicked state variable is updated as expected.

There are many other ways to test React components, including using React Testing Library to test components in a way that more closely resembles how a user would interact with them, and using Jest's mocking features to test asynchronous code and network requests.

Thank You

Thank you for visiting webdevmonk to read our React JS tutorial. We are grateful that you took the time to learn about React and we hope that you found the tutorial helpful.

We understand that learning a new technology can be challenging, and we encourage you to re-read the tutorial if you feel like you need more clarification or practice. Repetition is a great way to solidify your understanding and improve your skills.

Thank you again for choosing Web Dev Monk as your learning resource. We hope to see you again soon