A Comprehensive Guide to Setting Up a React.js Project in Your Local Environment

Page Visited: 1535
Read Time:4 Minute, 46 Second

ReactJs is one of the most popular JavaScript Libraries for creating user interfaces. Setting up a ReactJs project in your local environment is the first step towards creating powerful web applications. This article will guide you through the process of setting up a ReactJs project in your local environment, with an example.

Requirements

Before we dive into setting ReactJs in your local environment, make sure you have the following requirements installed on your local machine:

  1. Node.js and npm (Node Package Manager): Node.js is a JavaScript runtime that allows you to execute JavaScript code outside of a web browser. npm is a package manager that comes bundled with Node.js, allowing you to install and manage dependencies.

Step 1: Install Node.js and npm:

  • Download the Latest LTS (Long Term Support) version for your operating system of NodeJs from the NodeJs official website (https://nodejs.org)
  • Follow the installation instructions provided by the Node.js installer. Make sure to select the option to include npm during the installation process.
  • Open the command prompt by pressing WIN+R and typing cmd prompt to verify that the NodeJs and NPM are installed correctly, using this command:
node --version
npm --version

Step 2: Create a New ReactJs Project:

  • Once you have Node.js and npm installed, you can use a tool called create-react-app to set up a new ReactJs project quickly.
  • Open a terminal or command prompt and run the following command to install create-react-app globally:
npm install -g create-react-app

If you get an error after installing the ReactJS app, try running this code

npm update -g create-react-app
local setup
  • Once the installation is complete, navigate to the directory where you want to create your project.
  • Run the following command to create a new ReactJs project:
npx create-react-app my-react-app
writing code on command prompt

Replace my-react-app with the desired name of your project.

  1. This command “create-react-app” will generate a new project in the directory “my-react-app“. You can navigate to the project directory using this command:
cd my-react-app

Step 3: Start the React Development Server:

  • Now that your ReactJs project is set up, it’s time to start the development server.
  • In the terminal or command prompt, run the following command
npm start
writing code on command prompt
  • This command will start the development server and open your default web browser, displaying the ReactJs application.
  • You can make changes to the project files, and the development server will automatically update the application in the browser.

Congratulations! You have successfully set up a ReactJs project in your local environment. You can now start building your ReactJs application by modifying the files in the src directory.

Setting Up a ReactJs in local Environment

Now for an example, This example will use Newsapi to list out the top headlines

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

const App = () => {
  const [headlines, setHeadlines] = useState([]);

  useEffect(() => {
    fetchNewsHeadlines();
  }, []);

  const fetchNewsHeadlines = async () => {
    try {
      const apiKey = 'YOUR_API_KEY'; // Replace with your News API key
      const response = await fetch(
        `https://newsapi.org/v2/top-headlines?country=us&apiKey=${apiKey}`
      );
      const data = await response.json();
      setHeadlines(data.articles);
    } catch (error) {
      console.log('Error fetching news headlines:', error);
    }
  };

  return (
    <div>
      <h1>Latest Headlines</h1>
      {headlines.map((headline, index) => (
        <div key={index}>
          <h2>{headline.title}</h2>
          <p>{headline.description}</p>
          <hr />
        </div>
      ))}
    </div>
  );
};

export default App;

You have to add this code in src/app.js. You need signup on the News API website (https://newsapi.org) to get the free API. Replace ‘YOUR_API_KEY‘ with your actual API key in the fetchNewsHeadlines function.

Setting Up a ReactJs in local Environment

Explanation:

  1. The code starts by importing the necessary React hooks (useState and useEffect) and sets up a functional component called App.
  2. Inside the component, a state variable headlines is created using the useState hook. It will store the array of fetched headlines.
  3. The useEffect hook is used to fetch the news headlines when the component mounts. The fetchNewsHeadlines function is called within the useEffect hook.
  4. The fetchNewsHeadlines function makes an asynchronous HTTP request using fetch the News API endpoint. It uses the await keyword to wait for the response and converts it to JSON.
  5. If the request is successful, the retrieved articles are stored in the headlines state using the setHeadlines function.
  6. If there’s an error during the API call, it will be caught and logged into the console.
  7. The JSX code in the return statement renders the headlines on the screen. It uses the map function to iterate over the headlines array and display each headline’s title and description.
  8. The rendered headlines are wrapped in an div element, and a horizontal rule (<hr/>) is added after each headline for visual separation.

Remember to replace 'YOUR_API_KEY' with your actual API key for the News API. Additionally, you can customize the API endpoint and parameters based on your specific requirements (e.g., country, category, etc.).

That’s it! With this code, you can display the latest headlines from top news websites in your ReactJs application. Happy coding!

Conclusion

Setting up a ReactJs project in your local environment is a crucial first step in building web applications using React. By following the steps outlined in this article, you should now have a fully functional ReactJs project running on your machine. Remember to keep Node.js and npm updated to leverage the latest features and security fixes. Happy coding!

We also have a guide for setting angular in your local environment, let us know in the comments if you like this kind of article, and we will create this for more programming languages.

About Post Author

Girish

Hello Guys I am a website developer by profession but is always keen on learning new things. I have been investing in Mutual funds, stock market for the past few years because of which I have gained good knowledge. I started my entrepreneur journey in 2019 which lead me to learn more things as I am moving forward. I always love to share whatever I learn. Always had a craze for cars from my childhood, which inspired me to start this website.
Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

Girish

Hello Guys I am a website developer by profession but is always keen on learning new things. I have been investing in Mutual funds, stock market for the past few years because of which I have gained good knowledge. I started my entrepreneur journey in 2019 which lead me to learn more things as I am moving forward. I always love to share whatever I learn. Always had a craze for cars from my childhood, which inspired me to start this website.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Enable Notifications OK No thanks