React JS Tutorial – An Easy Step-by-Step Guide To Learn React

Last updated on Jan 10,2024 77K Views

Shivaprakash
Shivaprakash is a Research analyst at Edureka. He has expertise on front... Shivaprakash is a Research analyst at Edureka. He has expertise on front end web technologies like jQuery and React JS. He is also passionate...
1 / 2 Blog from React Basics

The ‘react’ tag appears in more than 114,000 publications. The library is widely used, and React is a large developer community that includes Facebook programmers. Anyone around the globe can ask a specialist a question and receive an answer from that expert. Here in this React js tutorial blog, you will understand everything about react js, so without further ado, let’s get started with the content.

React js tutorial

Contents:

What is react js 

Why do we use react js

Interesting facts about react js

Pros and cons of react js

Prerequisite to learn to react js

Setting up a React js Development Environment

Understanding the React js Components

State and Props in React js

Lifecycle methods in React js

Event handling in React js

Working with Forms in React js

React Router

Adding animation to React js components

Best practices for working with React js

To-do list project in react js

If you are not into reading, then you can also check our full course

ReactJS Full Course in 7 Hours | Learn React js | React.js Training | Edureka



What is react js 

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

React is designed to make it easy to build reusable UI components. It allows you to declaratively describe your UI using JSX, a syntax extension for JavaScript that lets you write HTML-like code. When your component renders, React creates a virtual DOM (a lightweight in-memory representation of the actual DOM) and compares it to the previous virtual DOM to determine the minimum number of DOM updates that need to be made. This can help improve the performance of your application, especially if you have a large amount of data that needs to be displayed.

React also provides a powerful programming model for managing state and handling interactions. You can use React’s useState hook to add state to functional components, and the useEffect hook to perform side effects (such as fetching data or subscribing to events).

Why do we use react js?

There are several reasons why developers might choose to use ReactJS:

Reusable components: One of the key benefits of React is that it allows you to build reusable components that can be shared among different parts of your application. This can help you write more maintainable code and reduce duplication of effort.

Virtual DOM: React uses a virtual DOM to improve the performance of your application. When you update the state of a component, React will compare the new virtual DOM with the previous version to determine the minimum number of DOM updates that need to be made. This can help reduce the number of costly DOM manipulation operations, which can improve the overall performance of your application.

Declarative syntax: React allows you to declaratively describe your UI using JSX, a syntax extension for JavaScript that lets you write HTML-like code. This can make your code easier to read and understand, especially for developers who are familiar with HTML.

Popularity and community support: React is a widely used and well-supported library, with a large and active developer community. This can make it easier to find resources and help when you are working with React, and also helps to ensure that the library is well-maintained and up-to-date.

Interesting facts about react js for introduction

    1. React was developed by a software engineer at Facebook named Jordan Walke.
    2. The name “React” was chosen because the library was designed to respond to changes in the user interface.
    3. React was first used internally at Facebook in 2011, and was released as open-source in 2013.
    4. React has a virtual DOM (Document Object Model) that allows it to update the UI efficiently by only rendering the components that have changed.
    5. React follows a declarative programming style, which means that developers can describe how the UI should look and behave, and React will take care of the rest.
    6. React has a thriving community of developers and contributors, with over 1,000 contributors on GitHub.
    7. React has a strong focus on performance, with features like the virtual DOM and lazy loading helping to optimize the rendering of components.

  1. React has been used to build some of the most popular applications in the world, including Facebook, Airbnb, Netflix, and many others.
  2. React has inspired the development of other

Enhance your design skills with our top-rated UX design course.

React JS Pros and Cons

Here are some pros and cons of using React:

Pros:

  • Reusable components: React allows you to build reusable UI components, which can significantly reduce the time and effort spent on building and maintaining large applications.
  • Virtual DOM: React uses a virtual DOM (Document Object Model) to optimize updates to the actual DOM. This means that rather than updating the entire DOM tree when the state of a component changes, React only updates the specific components that have changed, which can improve the performance of your application.
  • Ecosystem: React has a large and active community, which has led to the development of a number of tools, libraries, and frameworks that can be used with React, such as Redux and GraphQL.

Cons:

    • Steep learning curve: React has a steep learning curve, especially for developers who are new to front-end development or who are not familiar with modern JavaScript syntax.
    • JSX syntax: React uses JSX, a syntax extension for JavaScript, which can be confusing for developers who are not familiar with it.
    • Limited to the view layer: React is limited to the view layer of an application, so if you want to build a complete web application, you will need to use additional libraries or frameworks to handle things like routing and state management.

    Prerequisite to learn to react js 

    To learn React JS, it is helpful to have a basic understanding of the following concepts:

    HTML and CSS: React is a JavaScript library, so you’ll need to have a basic understanding of HTML and CSS to use it effectively.

    JavaScript: React is a JavaScript library, so you’ll need to have a strong understanding of JavaScript to use it effectively.

    ES6 syntax: React uses modern JavaScript syntax, so it is helpful to have a basic understanding of ES6 syntax and features such as arrow functions, destructuring, and the spread operator.

    The Document Object Model (DOM): React uses a virtual DOM to update the actual DOM, so it is helpful to have a basic understanding of how the DOM works.

    Node.js: React is often used in combination with Node.js, so it is helpful to have a basic understanding of how to use Node.js.

    npm: npm is the package manager for Node.js, and is used to install and manage packages (including React) in a Node.js project. It is helpful to have a basic understanding of npm.

    Setting up a React js Development Environment

    Create ReactJS Project

    To set up a new React project, you can use the following steps:

    1. Install Node.js: React is built using JavaScript and requires Node.js to be installed on your computer. You can download and install the latest version of Node.js from the official website (https://nodejs.org/).
    2. Install the React CLI (Command Line Interface): The React CLI is a command-line tool that you can use to create and manage React projects. You can install it using the following command:

    npm install -g react-cli

    1. Create a new project: To create a new React project, you can use the following command:

    react-cli create my-project

    This will create a new directory called “my-project” with the basic structure of a React project.

    1. Install dependencies: Navigate to the project directory and install the necessary dependencies using the following command:

    npm install

    This will install all of the necessary packages and libraries that are required for your project.

    1. Start the development server: To start the development server, you can use the following command:

    npm start

    This will start the development server and open a new browser window with your React app. You can now start building your React app.

Find out our React Course in Top Cities

IndiaOther Popular Cities
React JS Course in ChennaiReact JS Course in Australia
React JS Course in BangaloreReact JS Course in Canada
React JS Course in HyderabadReact JS Course in Singapore
  • Understanding the React Components

    In React, a component is a piece of code that represents a part of the UI (User Interface). Components are reusable, which means that you can use the same component multiple times in your application.

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

    Functional components are simple functions that accept props (short for properties) as input and return a React element. They are easy to write and understand, and they are a good choice for simple components that do not have state or lifecycle methods.

    Class-based components are defined using a class that extends React. Component class. They can have state, lifecycle methods, and other features that are not available to functional components. Class-based components are a good choice for more complex components that need to manage a state or perform other advanced tasks.

    Here is an example of a functional component that displays a simple message:

    
    import React from 'react';
    
    const Message = (props) => {
    
    return <p>{props.message}</p>;
    
    }
    
    export default Message;
    
    And here is an example of a class-based component that displays a message and has a button to toggle the message between two different values:
    
    import React, { Component } from 'react';
    
    class Message extends Component {
    
    constructor(props) {
    
    super(props);
    
    this.state = { message: 'Hello World' };
    
    }
    
    toggleMessage = () => {
    
    this.setState((prevState) => ({
    
    message: prevState.message === 'Hello World' ? 'Goodbye World' : 'Hello World'
    
    }));
    
    }
    
    render() {
    
    return (
    
    <div>
    
    <p>{this.state.message}</p>
    
    <button onClick={this.toggleMessage}>Toggle Message</button>
    
    </div>
    
    );
    
    }
    
    }
    
    export default Message;
    
    

    To use a component in another part of your application, you can import it and use it like a regular HTML tag. For example:

    
    import Message from './Message';
    
    const App = () => {
    
    return (
    
    <div>
    
    <Message message="Hello from the App component" />
    
    </div>
    
    );
    
    }
    
    

    State and Props in React

    In React, state and props are both used to store and manage data in a component.

    Props (short for properties) are values that are passed to a component from its parent component. Props are used to customize the behavior and appearance of a component, and they are read-only, which means that a component cannot modify its own props.

    State is a feature of class-based components that allows a component to store and manage its own internal data. State is used to track changes to a component’s data, and it can be modified within the component using the setState method.

    Here is an example of a component that uses both state and props:

    
    import React, { Component } from 'react';
    
    class Counter extends Component {
    
    constructor(props) {
    
    super(props);
    
    this.state = { count: 0 };
    
    }
    
    increment = () => {
    
    this.setState((prevState) => ({ count: prevState.count + 1 }));
    
    }
    
    render() {
    
    return (
    
    <div>
    
    <p>{this.props.message}: {this.state.count}</p>
    
    <button onClick={this.increment}>Increment</button>
    
    </div>
    
    );
    
    }
    
    }
    
    export default Counter;
    
    

    In this example, the Counter component has a state called count that is used to store the current value of the counter. The component also has a prop called message that is used to customize the message that is displayed. The increment method is used to update the count state when the button is clicked.

    To use the Counter component, you can pass it a message prop like this:

    <Counter message="The current count" />

    This will display a message with the current count and a button to increment the count. The count will be stored in the component’s state and will be updated automatically when the button is clicked.

    Lifecycle methods in React js

    Lifecycle methods are methods that are called at certain points in a component’s lifecycle. These methods allow you to trigger an action at a specific point in time in the lifecycle of a component.

    In React, there are several lifecycle methods:

    1. componentDidMount: called after the component is rendered.
    2. shouldComponentUpdate: called before the component is re-rendered. You can use this to optimize performance by returning false if you know the component does not need to update.
    3. componentDidUpdate: called after the component is updated.
    4. componentWillUnmount: called before the component is unmounted from the DOM.
    5. componentDidCatch: called if there is an error during rendering, in a lifecycle method, or in the constructor of any child component.
    
    class MyComponent extends React.Component {
    
    componentDidMount() {
    
    // called after the component is rendered
    
    console.log('Component did mount!')
    
    }
    
    componentDidUpdate() {
    
    // called after the component is updated
    
    console.log('Component did update!')
    
    }
    
    componentWillUnmount() {
    
    // called before the component is unmounted from the DOM
    
    console.log('Component will unmount!')
    
    }
    
    render() {
    
    return &amp;lt;div&amp;gt;Hello World!&amp;lt;/div&amp;gt;
    
    }
    
    }
    
    

    Event handling in react js 

    In React, you can handle events in a similar way to how you handle events in HTML. The syntax for handling an event in a React component is:

    
    &amp;lt;button onClick={this.handleClick}&amp;gt;Click me&amp;lt;/button&amp;gt;
    
    

    Here, handleClick is the event handler that will be called when the button is clicked. You can define the handleClick function in your component like this:

    
    class MyComponent extends React.Component {
    
    handleClick() {
    
    console.log('Button clicked!')
    
    }
    
    render() {
    
    return &amp;lt;button onClick={this.handleClick}&amp;gt;Click me&amp;lt;/button&amp;gt;
    
    }
    
    }
    
    

    You can also pass an anonymous function as the event handler:

     
    &amp;lt;button onClick={() =&amp;gt; console.log('Button clicked!')}&amp;gt;Click me&amp;lt;/button&amp;gt;
    
    

    Working with Forms in React

    In React, you can create forms in a similar way to how you create forms in HTML. Here is an example of a simple form in React:

    
    class MyForm 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 (
    
    &amp;lt;form onSubmit={this.handleSubmit}&amp;gt;
    
    &amp;lt;label&amp;gt;
    
    Name:
    
    &amp;lt;input
    
    type="text"
    
    name="name"
    
    value={this.state.name}
    
    onChange={this.handleChange}
    
    /&amp;gt;
    
    &amp;lt;/label&amp;gt;
    
    &amp;lt;br /&amp;gt;
    
    &amp;lt;label&amp;gt;
    
    Email:
    
    &amp;lt;input
    
    type="email"
    
    name="email"
    
    value={this.state.email}
    
    onChange={this.handleChange}
    
    /&amp;gt;
    
    &amp;lt;/label&amp;gt;
    
    &amp;lt;br /&amp;gt;
    
    &amp;lt;button type="submit"&amp;gt;Submit&amp;lt;/button&amp;gt;
    
    &amp;lt;/form&amp;gt;
    
    )
    
    }
    
    }
    
    

    React Router

    React Router is a popular library for handling routing in a React application. It allows you to define the routes for your app and the components that should be rendered for each route.

    To use React Router, you will need to install it first:

    npm install react-router-dom

    Then, you can use the BrowserRouter component to wrap your app, and the Route component to define your routes:

    
    import { BrowserRouter, Route } from 'react-router-dom'
    
    const App = () =&amp;gt; {
    
    return (
    
    &amp;lt;BrowserRouter&amp;gt;
    
    &amp;lt;Route exact path="/" component={Home} /&amp;gt;
    
    &amp;lt;Route path="/about" component={About} /&amp;gt;
    
    &amp;lt;Route path="/contact" component={Contact} /&amp;gt;
    
    &amp;lt;/BrowserRouter&amp;gt;
    
    )
    
    }
    
    


    In this example, we have three routes: /, /about, and /contact. The Home component will be rendered for the / route, the About component will be rendered for the /about route, and the Contact component will be rendered for the /contact route.

    Adding animation to React components

    There are several ways to add animation to React components. Here are a few options:

    1. Using the animation and transition CSS properties: You can use these properties to define animation keyframes and transitions between different states of an element.
    2. Using a CSS animation library: There are several libraries, such as Animate.css and Lottie, that provide pre-built animation classes that you can use in your React components.
    3. Using a JavaScript animation library: Libraries like GSAP and Velocity.js allow you to create more complex animations using JavaScript.
    4. Using the react-transition-group library: This library provides a set of components that you can use to add transitions between elements in your React app.

    Here is an example of how you can use the react-transition-group library to add a fade-in transition to a component:

    
    import { CSSTransition } from 'react-transition-group'
    
    const FadeInComponent = () =&amp;gt; {
    
    return (
    
    &amp;lt;CSSTransition
    
    in={true}
    
    appear={true}
    
    timeout={1000}
    
    classNames="fade"
    
    &amp;gt;
    
    &amp;lt;div&amp;gt;I will fade in&amp;lt;/div&amp;gt;
    
    &amp;lt;/CSSTransition&amp;gt;
    
    )
    
    }
    
    


    In this example, the FadeInComponent will fade in over a period of 1 second (defined by the timeout prop) when it is mounted. You will also need to define the fade class in your CSS with the desired animation properties.

    Best practices for working with React

    Here are a few best practices for working with React:

    Use functional components as much as possible: Functional components are easier to write and understand, and they are also more performant than class-based components.

    Use the useEffect hook for side effects: The useEffect hook allows you to perform side effects (such as data fetching or subscriptions) in functional components.

    Use the useCallback hook to optimize performance: The useCallback hook allows you to memoize functions so that they are not recreated on every render. This can be helpful for optimizing performance, especially when passing down expensive functions as props.

    Use the useMemo hook for expensive calculations: The useMemo hook allows you to memoize values that are expensive to calculate. This can help improve the performance of your app by avoiding unnecessary re-calculations.

    Use the useReducer hook for managing state: The useReducer hook is a powerful alternative to the useState hook, and it can be helpful for managing complex state in your app.

    Use the react-testing-library for testing: The react-testing-library is a popular library for testing React components. It provides a simple and intuitive API for testing components in a way that is closer to how users interact with them.

    To-do list project in react js 

    Certainly! Here is some sample code that you can use to create a simple to-do list in ReactJS with inline comments explaining each part of the code:

    
    import React, { useState } from 'react';
    
    function ToDoList() {
    
    // Declare state variables to store the list of tasks and the value of the text input
    
    const [tasks, setTasks] = useState([]);
    
    const [newTask, setNewTask] = useState('');
    
    // Define an event handler for submitting the form
    
    const handleSubmit = (event) =&amp;gt; {
    
    // Prevent the default form submission behavior
    
    event.preventDefault();
    
    // Add the new task to the list if the input is not empty
    
    if (newTask.trim()) {
    
    setTasks([...tasks, newTask]);
    
    setNewTask('');
    
    }
    
    };
    
    // Define an event handler for changing the value of the text input
    
    const handleChange = (event) =&amp;gt; {
    
    setNewTask(event.target.value);
    
    };
    
    // Define an event handler for clearing all tasks from the list
    
    const handleClear = () =&amp;gt; {
    
    setTasks([]);
    
    };
    
    return (
    
    &amp;lt;div&amp;gt;
    
    &amp;lt;h1&amp;gt;To-Do List&amp;lt;/h1&amp;gt;
    
    {/* Render the form for adding new tasks */}
    
    &amp;lt;form onSubmit={handleSubmit}&amp;gt;
    
    &amp;lt;input type="text" value={newTask} onChange={handleChange} /&amp;gt;
    
    &amp;lt;button type="submit"&amp;gt;Add Task&amp;lt;/button&amp;gt;
    
    &amp;lt;/form&amp;gt;
    
    {/* Render a button for clearing all tasks */}
    
    &amp;lt;button onClick={handleClear}&amp;gt;Clear All&amp;lt;/button&amp;gt;
    
    {/* Render the list of tasks */}
    
    &amp;lt;ul&amp;gt;
    
    {tasks.map((task, index) =&amp;gt; (
    
    &amp;lt;li key={index}&amp;gt;{task}&amp;lt;/li&amp;gt;
    
    ))}
    
    &amp;lt;/ul&amp;gt;
    
    &amp;lt;/div&amp;gt;
    
    );
    
    }
    
    export default ToDoList;
    
    

     

    output

    So this is how the output looks like we will have a To – Do List heading, a text box to enter the tasks , add task button and a clear all button.

    output react js

    once you write the task in the text box you can add the task by clicking the add task button

     

    add task React js

    This is how the final output after you add the tasks

    All task React js

     

    This brings us to the end of this article where we have learned React js. I hope you have a clear understanding of everything that has been shared with you in this blog. If you have additional questions or suggestions, please leave a comment below and we will get back to you as soon as possible.

    Join a Flutter certification course and learn how to create visually stunning mobile app UIs that capture your users’ attention.

  • If you found this article on “React js Tutorial” relevant, check out the Edureka’s React JS  certification training course, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. If you come across any questions, feel free to ask all your questions in the comments section of “React tutorial,” and our team will be glad to answer.
Upcoming Batches For React.js Training Course With Certification
Course NameDateDetails
React.js Training Course With Certification

Class Starts on 30th March,2024

30th March

SAT&SUN (Weekend Batch)
View Details
Comments
1 Comment
  • kalyn says:

    Recent survey reveals that on average 75% men and women are involved into internet activities. Internet arena has grown into bigger and even better and bringing lots of opportunities. Working at home online tasks are trending and improving individual’s everyday lives. The key reason why it is actually extremely popular? Simply because it enables you to work from anywhere and anytime. You are able to get much more time to invest with all your family and can plan out journeys for vacations. Men and women are making wonderful earnings of $17000 each week by utilizing the efficient and smart ways. Doing right work in a right direction will definitely lead us in the direction of becoming successful. You will start to earn from the 1st day as soon as you explore our site. >>>>> CONTACT US TODAY

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

React JS Tutorial – An Easy Step-by-Step Guide To Learn React

edureka.co