Nabarun
React.js is a popular JavaScript library used for building user interfaces. It was developed by Facebook and has gained a lot of traction in recent years. React allows developers to build reusable UI components and manage the state of the application in a simple and efficient manner. In this blog post, we will discuss how to get started with React.js as a beginner using functional components.
A JavaScript package called React.js is used to create user interfaces. It is more of a library with an emphasis on the view layer of an application than a whole framework like Angular or Vue.js. React enables developers to create reusable UI components and easily and effectively control the application's state.
Components are reusable code blocks that may be combined to construct sophisticated user interfaces, and they are the foundation upon which the library is built. With React, each component is a JavaScript function that can have its own state and properties and outputs a piece of the user interface.
There are few prerequisites you should have in place before we begin the coding:
After these conditions are met, you can move forward with the following actions:
Step 1: Preparing the environment
You must set up a development environment on your PC before you can begin using React. Typically, Node.js and the Node Package Manager are used to create React applications (npm).
Installing Node.js on your machine is the first step. The most recent version of Node.js is available for download from the official website.
Open a terminal window after installing Node.js and use the following command to see if it was installed correctly:
node -v
You have successfully installed Node.js if the command returns the version of the software that is now running on your computer.
The create-react-app package must then be installed on your system globally using the following command:
npm install -g create-react-app
With the aid of this package, a React project can be quickly and easily set up with all of the required dependencies and parameters.
Step 2: Starting a fresh React project
With the create-react-app command after setting up the environment, you can now start a new React project:
create-react-app my-app
This command will create a new React project in a folder named my-app.
Step 3: Running the application
To run the React application, navigate to the project folder using the terminal and run the following command:
npm start
This command will start both your default web browser and the program's local development server. The screen should display a welcome message informing you that the application is currently running.
Step 4: Comprehend the project's structure
Before we start writing code, let's spend some time understanding the project structure created by create-react-app:
my-app/
README.md
node_modules/
package.json
public/
index.html
favicon.ico
src/
App.js
App.css
index.js
logo.svg
The primary source code for the programme is located in the src folder. The application's entry point, App.js, houses the primary React component. The primary component's rendering to the DOM is done via the index.js file.
Static resources including HTML, CSS, and pictures are found under the public folder. The primary HTML file for the programme is index.html.
Each project dependency is located in the node modules folder.
The setup and metadata for the project are contained in the package.json file.
Step 5: Making a straightforward React component
Let's build a straightforward React component now that we have a foundational grasp of the project's structure. Open your text editor and add the following code to the App.js file in place of the current code:
import React from 'react';
function App() {
return (
<div>
<h1>Hello, World!</h1>
<p>Welcome to my React app.</p>
</div>
);
}
export default App;
The following functional component, named App, returns a UI comprising an h1 element and a p element. Utilizing JSX syntax, which combines HTML and JavaScript, this component must return a single root element, here defined as a div element.
Step 6: Creating the component
Open the index.js file and add the following code to the current lines to render the App component to the DOM:
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
The React and ReactDOM frameworks, as well as the App component, are imported by this code. The App component is rendered to the DOM using the root.render() function. The StrictMode element is additionally used to turn on the stringent mode for the application.
Step 7: Viewing the component
Go to the browser window where your React application is running after saving both files. You ought to notice the message "World, welcome! Please enjoy my React app "showing up on the screen.
Congratulations—you've just finished rendering and creating your first React component!
Working with Props
Data can be passed from a parent component to a child component via props. They enable you to reuse components with varied data, increasing the modularity and flexibility of your code.
Let's build a new prop-accepting component. Edit the App.js file and add the following code to the current lines:
import React from 'react';
function Welcome(props) {
return (
<div>
<h1>Hello, {props.name}!</h1>
<p>{props.message}</p>
</div>
);
}
function App() {
return (
<div>
<Welcome name="Alice" message="Welcome to my React app." />
<Welcome name="Bob" message="Thanks for visiting." />
</div>
);
}
export default App;
The Welcome component, which takes two arguments (name and message), is being created in this code. To dynamically show a welcome message for the user, we are using these props.
Two instances of the Welcome component with various props are being rendered in the App component. We can utilize the same component with various data as a result of this.
File saving followed by a browser window refresh, One greeting for Alice and one for Bob should appear on the screen simultaneously.
Using State
A component's state is how data are managed and stored there. You may make dynamic, interactive UIs using this tool.
Let's create a new component that uses state. Open the App.js file and replace the existing code with the following:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<h1>Count: {count}</h1>
<button onClick={handleClick}>Increment</button>
</div>
);
}
function App() {
return (
<div>
<Counter />
</div>
);
}
export default App;
The useState hook is used in this code to handle the count state of a new component we're calling Counter. The useState hook returns an array with two elements: a method to update the state (setCount) and the current value of the state (count).
Also, we are developing a function called handleClick that, when the user presses the Increment button, updates the count state. The onClick event handler of the button element receives this method as a callback.
We are rendering a Counter component instance in the App component. This element shows the current count and an incrementing button.
Save the file and refresh the browser window. You should see a Counter component displayed on the screen. Clicking the Increment button should update the count state and display the new value.
Making Use Of useEffect
A component can conduct side effects (such as retrieving data or modifying the DOM) by using an effect. It enables you to divide concerns and maintain order in your code.
Let's build a brand-new effect-using component. Edit the App.js file and add the following code to the current lines:
import React, { useState, useEffect } from 'react';
function RandomNumber() {
const [number, setNumber] = useState(null);
useEffect(() => {
const timer = setInterval(() => {
const newNumber = Math.floor(Math.random() * 100);
setNumber(newNumber);
}, 1000);
return () => {
clearInterval(timer);
};
}, []);
return (
<div>
<h1>Random Number: {number}</h1>
</div>
);
}
function App() {
return (
<div>
<RandomNumber />
</div>
);
}
export default App;
The useState and useEffect hooks are used to create a new component called RandomNumber in this code. A numerical state is managed by the useState hook, and it is updated every second by the useEffect hook.
We are constructing a timer that executes a function to produce a new random number and update the number state inside the useEffect hook. Also, a cleanup function that resets the timer once the component unmounts is returned.
We are rendering a RandomNumber component instance in the App component. This element refreshes the random number it displays once every second.
Refresh the browser window after saving the file. A RandomNumber component ought to appear on the screen. The number should change every second.
Conclusion
We have discussed the fundamentals of React.js and how a newbie can get started in this blog post. Topics like starting a project, making components, utilizing properties, using state, and using effect have all been addressed.
A strong and adaptable library for creating user interfaces is react.js. It can be applied to a wide range of applications, from straightforward websites to sophisticated web programs.
Learning all the React.js ideas and best practices as a newbie can be difficult. But if you put in the time and effort, you can master this library and begin creating your own projects.
I sincerely hope that this blog post has helped you get started with React.js. Happy coding!
Hey! I'm a Software Developer currently based in India. I love being an autodidact as it enables my curious mind to thrive. I'm Dev #369 at Developer DAO and a member of DAOpunks.