React.js is still one of the most widely used and sought-after web frameworks in the world. More than 40% of software engineers globally utilize React to create online applications, according to data from recent years. React is preferred by businesses because it enables them to create systems that are easy to maintain and scalable, both of which are essential for expansion. Read through this React JS tutorial for beginners and get started with our React course syllabus.
React JS Basic Concepts
Here are the foundational concepts of React for beginners to know:
React JS Introduction
A JavaScript package called React is used to create user interfaces, or UI elements. Consider it a collection of technologies that assist programmers in creating dynamic and interactive web applications.
- Component-Based: UIs are constructed by disassembling them into reusable parts known as components.
- Virtual DOM: React is using virtual DOM. It functions similarly to a thin memory copy of the actual DOM.
- Declarative: React handles changing the DOM to correspond with your definition of how your user interface (UI) should appear in various application stages.
- Unidirectional Data Flow: Usually, data moves from parent components to child components in a single direction.
- Big and Active Community: There are a lot of resources available because React has a large and encouraging community.
- Versatile: React is mostly used for web development, but it can also be used to create desktop apps and mobile apps (using React Native).
By offering an organized and effective method of managing the user interface, React streamlines the process of creating intricate and dynamic front-end apps.
Recommended: React JS Online Course Program.
Setting up the Development Environment for React
Setting up the development environment for React is the first and crucial step. Here is the guide:
Node.js and npm (or yarn/pnpm): JavaScript and its ecosystem are essential components of React. npm (Node Package Manager) is the default package manager for Node.js, a JavaScript runtime environment.
Installing React, its dependencies, and other helpful tools will be done with npm (or substitutes like yarn or pnpm).
Installation:
- Visit https://nodejs.org/, the official Node.js website.
- For development, get the LTS (Long-Term Support) version, which is typically more stable.
- Start the installation and follow the on-screen instructions. With Node.js, npm will be installed automatically.
Verification:
- Launch the command prompt or terminal.
- Run the following to see if Node.js is installed:
node -v
- Run the following to see if npm is installed:
npm -v
- Version numbers need to be displayed in your terminal.
Suggested: Web Development Course in Chennai.
Code Editor
To write React code, you’ll need a competent code editor. Here are a few suggested choices:
- Visual Studio Code (VS Code): A free, robust, and extremely expandable editor, it offers first-rate support for React through extensions. The URL is https://code.visualstudio.com.
- Sublime Text: A quick and lightweight editor, Sublime Text offers both a free trial and a premium license. The website https://www.sublimetext.com/
- WebStorm: A robust and feature-rich integrated development environment (IDE) made especially for web development (paid). (Webstorm: https://www.jetbrains.com/)
Select the editor with whom you are most at ease. Because of its many features and free availability, Visual Studio Code is a widely popular option in the React community.
Basic React Project Structure
An official command-line tool called Create React App creates a simple React project with a logical default configuration. You can concentrate on building React code because it takes care of the underlying build tools and configurations.
Installation:
npm install -g create-react-app
(You can use it in any project directory because the -g flag installs it globally.)
Creating a React JS Beginner Project:
In the terminal, navigate to the directory where you wish to start your project.
Execute the subsequent command, substituting your preferred project name for my-app:
npx create-react-app my-app
(By utilizing npx, you can make sure you’re running the most recent version of create-react-app without having to install it everywhere.)
Navigating to Your Project:
cd my-app
Starting the Development Server:
npm start
This command will:
- Create your application using React.
- Launch a development server, which is typically located at http://localhost:3000.
- Launch the default web browser and see the React application in its simplest form.
Browser
To access your React apps, you will need a contemporary web browser.
- Edge, Safari, Firefox, and Chrome are all excellent choices.
- Installing the React Developer Tools browser extension (compatible with Chrome and Firefox) is something to think about.
Debugging is greatly facilitated by this addon, which offers insightful information about your React component hierarchy, properties, and state.
Optional but Recommended Tools:
- Git: A version control system that lets you work with others and keep track of code changes. The URL is https://git-scm.com.
- Yarn or pnpm: Alternative package managers like Yarn or pnpm occasionally have features or performance advantages over npm. (https://pnpm.io/ and https://yarnpkg.com/)
Recommended: MERN Stack Course in Chennai.
JSX (JavaScript XML) for React Development
One of the core ideas of React programming is JSX. Consider it a JavaScript syntactic extension that lets you create HTML-like structures right in your JavaScript code.
What is JSX?
Writing HTML inside your JavaScript code is similar to JSX. It’s a unique syntax that closely resembles HTML but incorporates all of JavaScript’s capabilities.
JavaScript:
const name = “World”;
const heading = <h1>Hello, {name}!</h1>;
In this snippet:
- <h1>Hi there, {name}!</h1> appears to be a typical HTML heading tag.
- The magic, however, occurs in the {name} section. It is a JavaScript expression that is directly included into the structure that resembles HTML. The name variable (in this case, “World”) will be evaluated by React and injected into the heading.
Why is JSX so useful?
- More Intuitive UI Development: JSX maintains the structure and functionality of your UI components tightly together, eliminating the need to juggle distinct HTML templates and the JavaScript logic that manipulates them.
- Readability: Many developers find it simpler to quickly comprehend code when they can see the user interface structure included right into the JavaScript of the component.
- Expressiveness: Any legitimate JavaScript expression can be inserted inside JSX’s curly braces. This makes it possible to render material dynamically depending on situations, data, and other factors.
- Under the Hood: Don’t let the syntax look like HTML. JSX is not immediately understood by browsers. React elements are created by converting JSX into standard JavaScript code using tools like Babel.
Key things to remember about JSX:
- It’s not exactly HTML: Some elements are processed differently, and attribute names (class becomes className, for example) change.
- One Root Element: There can only be one top-level element in a JSX expression. You must use a React Fragment (<> and ) or surround them in a parent element, such as a
- , if you wish to return several elements.
- JavaScript Expressions in Curly Braces: To incorporate JavaScript logic into your JSX, begin with {}.
JSX combines the power of JavaScript with HTML-like syntax to offer a more declarative and developer-friendly method of describing your user interfaces within your React components. It’s a fundamental component of what makes React programming fun and effective.
Core MERN Stack course in Chennai for beginners.
Writing JSX: Embedding Expressions, Attributes, Conditional Rendering, Lists
Effective JSX writing requires knowing how to handle attributes, render conditionally, display lists, and incorporate dynamic information. Let’s dissect each of these important elements using concrete examples.
Embedded Expressions:
Curly braces {} can be used to directly inject JavaScript values into your JSX. This is how you create a dynamic user interface.
function formatName(user) {
return user.firstName + ‘ ‘ + user.lastName;
}
const user = {
firstName: ‘John’,
lastName: ‘Doe’
};
const element = (
<h1>
Hello, {formatName(user)}!
</h1>
);
// You can even embed simple expressions directly:
const count = 5;
const message = <p>You have {count * 2} notifications.</p>;
A JavaScript expression will be evaluated for everything enclosed in curly braces {}. This can include arithmetic operations, variables, function calls, and more.
Working with Attributes:
There are some significant distinctions between setting attributes on JSX elements and HTML, but otherwise they are similar:
- className instead of class: Since class is a reserved keyword in JavaScript, you give CSS classes using className.
- htmlFor instead of for: Similarly, since for is a reserved keyword, labels are linked to input components using htmlFor.
- Camel Case for Custom Attributes: Camel case is usually used for React-specific or custom data attributes (for example, data-userId in HTML becomes dataUserId in JSX).
- Embedding Expressions in Attributes: Curly braces can also be used to embed JavaScript expressions inside attribute values.
Example:
const imageUrl = ‘https://via.placeholder.com/150’;
const altText = ‘Placeholder Image’;
const imageElement = (
<img src={imageUrl} alt={altText} className=”profile-image” data-user-id={123} />
);
function getAriaLabel(index) {
return `Button number ${index + 1}`;
}
const buttonElement = <button aria-label={getAriaLabel(0)}>Click Me</button>;
Conditional Rendering:
React offers multiple methods for conditionally rendering items according to specific criteria:
if/else Statements (Outside JSX): To decide what JSX to return from your component, you can utilize standard if/else statements.
function Greeting(props) {
if (props.isLoggedIn) {
return <h1>Welcome back!</h1>;
} else {
return <p>Please log in.</p>;
}
}
<Greeting isLoggedIn={true} /> {/* Renders: <h1>Welcome back!</h1> */}
<Greeting isLoggedIn={false} /> {/* Renders: <p>Please log in.</p> */}
Ternary Operator (condition ? exprIfTrue : exprIfFalse): This is a succinct method of handling basic conditional rendering in your JSX code.
function LoginButton(props) {
return (
<button onClick={props.onClick}>
{props.isLoggedIn ? ‘Logout’ : ‘Login’}
</button>
);
}
<LoginButton isLoggedIn={false} onClick={handleLogin} /> {/* Renders: <button>Login</button> */}
<LoginButton isLoggedIn={true} onClick={handleLogout} /> {/* Renders: <button>Logout</button> */}
Logical AND Operator (&&): The && operator can be used to render something only when a condition is true. The element after it will be rendered if the condition before && is true; if not, React will disregard it.
function Mailbox(props) {
const unreadMessages = props.messages.filter(message => !message.isRead);
return (
<div>
<h1>Hello!</h1>
{unreadMessages.length > 0 && (
<p>You have {unreadMessages.length} unread messages.</p>
)}
</div>
);
}
<Mailbox messages={[{ id: 1, isRead: true }, { id: 2, isRead: false }]} />
{/* Renders: <div><h1>Hello!</h1><p>You have 1 unread messages.</p></div> */}
<Mailbox messages={[{ id: 1, isRead: true }, { id: 2, isRead: true }]} />
{/* Renders: <div><h1>Hello!</h1></div> */}
Logical OR Operator (||): Although less frequently used for direct rendering, it allows you to supply a fallback value in the event that a variable is false.
const username = props.user && props.user.name || ‘Guest’;
// If props.user exists and has a name, username will be that name. Otherwise, it will be ‘Guest’.
Rendering Lists:
In React, lists of data are usually displayed by iterating over an array’s contents using the map() method, which returns JSX elements for each item. Each displayed item must have a unique key prop. This facilitates the efficient updating and re-rendering of list elements in React.
function NumberList(props) {
const numbers = props.numbers;
const listItems = numbers.map((number) => (
<li key={number.toString()}>
{number}
</li>
));
return (
<ul>{listItems}</ul>
);
}
const numbers = [1, 2, 3, 4, 5];
<NumberList numbers={numbers} />;
// Renders:
// <ul>
// <li key=”1″>1</li>
// <li key=”2″>2</li>
// <li key=”3″>3</li>
// <li key=”4″>4</li>
// <li key=”5″>5</li>
// </ul>
- Among the sibling elements, the key prop should be distinct.
- A solid identifier from your data, such as a database ID, is usually the best choice for the key.
- If the list’s item order changes, don’t use the array index as the key because this can cause unexpected behavior and performance problems.
Building reliable React apps requires an understanding of these JSX principles. You’ll feel very at ease writing expressive and dynamic user interface code if you practice utilizing them in many contexts.
Explore our full-stack developer course in Chennai.
Components in React
The fundamental units of any React application are called React components. Consider them separate, reusable code segments that specify a portion of your user interface and their functionality. They enable you to deconstruct intricate user interfaces into more manageable, reusable components.
In React, there are basically two types of components:
Functional Components / Stateless / Presentational Components:
- These are the simple components.
- They are basically JavaScript functions that return JSX (what to render on the screen) after accepting props (short for “properties”) as arguments.
- They lack their own internal state, or data that is subject to change within the component over time.
- Data that has been handed down from parent components is frequently shown via them.
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
<Welcome name=”Alice” /> {/* Renders: <h1>Hello, Alice!</h1> */}
<Welcome name=”Bob” /> {/* Renders: <h1>Hello, Bob!</h1> */}
Features of Functional Components:
- Plain JavaScript functions.
- Receive data via props.
- Focus on rendering UI based on props.
- No internal state.
- Generally simpler and easier to test.
Modern Functional Components (using Arrow Functions): Arrow function syntax, which is more condensed, is frequently used to write functional components:
const Greeting = (props) => {
return <p>Welcome, {props.user.username}!</p>;
};
<Greeting user={{ username: ‘Charlie’ }} /> {/* Renders: <p>Welcome, Charlie!</p> */}
Class Components / Stateful / Container Components:
- These classes in JavaScript are extensions of React.Component.
- By using the this.state property, they can have their own internal state that enables them to manage and update data over time, causing the user interface to re-render.
- They may have lifecycle methods (such as componentDidMount, componentDidUpdate, and componentWillUnmount) that let you take action at particular stages of the component’s lifecycle.
- Components that must manage their own data, retrieve data, or handle user interactions usually employ them.
import React from ‘react’;
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
this.increment = this.increment.bind(this);
}
increment() {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
<Counter /> {/* Renders a counter with an increment button */}
Features of Class Components:
- JavaScript classes that extend Respond.part.
- Can be in a state of their own.
- Lifecycle techniques are possible.
- Frequently deal with data processing and logic.
- Able to use props to transfer information to child functional components.
Related Course: AngularJS training in Chennai.
Properties of React Development
One essential method for transferring data from a parent component to its child components is through properties, often known as props. In the context of React components, they are read-only bits of data that give parent components the ability to manage and alter how their children are rendered. Think of them as arguments you pass to a function.
Passing Data Down:
- The main method by which parent components communicate with child components is through props.
- These properties are accessible within the child component after the parent component adds them to the JSX tag of the child component.
Read-Only Nature:
- It is never appropriate for child components to alter the props they are given directly. Props are intended to be read-only from the child’s point of view.
- In order for the parent component to update its own state, which may result in the passing down of new props, a child component that needs to modify data depending on props should communicate back to it (often by passing a callback function as a prop).
This makes it simpler to comprehend how data changes in your application by enforcing a unidirectional data flow.
Arbitrary Data Types:
Any valid JavaScript value can be passed as a prop, such as:
- Strings
- Numbers
- Booleans
- Objects
- Arrays
- Functions
- Even other React elements!
props Object:
- All of the passed props are accessible as properties of a single props object within a child component.
- This props object is supplied as the function’s initial (and frequently sole) argument in functional components.
- In class components, you access the props through this.props.
Default Props:
If the parent component doesn’t include default values for props, you can create them yourself. This offers fallback behavior and aids in error prevention.
Prop Validation (using propTypes – now a separate package):
- React is still usable even if it is currently available as a separate package.
- Prop validation alerts you if a component receives the incorrect kind of props or if necessary props are missing, which helps you identify any issues early in the development process.
In React, props are the means by which parent components interact and provide data to their offspring. They enable dynamic and reusable user interface structures and are read-only for the child component. Building well-structured and stable React applications requires an understanding of how to pass and use props.
Must Learn with React: MongoDB course in Chennai.
States in React Development
Another key idea in React is state, which gives your components their dynamic and interactive qualities. State is internal to a component and is subject to change over time, in contrast to props, which are read-only for the child and are sent down from parent components. React re-renders a component to update the user interface when its state changes.
Internal Data Management: Information that the component itself must maintain and perhaps update in response to user input, network requests, or other events is stored in state.
Only in Class Components (Historically): State was previously limited to React class components. This.state = {} would be used to initialize the state in the constructor, and this.setState() would be used to update it.
this.setState() for Updates:
- This kind of direct state modification is never appropriate.state.count = 5. For React to effectively re-render the component, it must be aware of state changes.
- You use this instead.the setState() function. This method schedules an update to the state of the component and accepts an object or function as an argument. After that, React will render the component and its offspring again.
- It is safer to use a function as the input if you need to update the state based on the previous state because setState() can be asynchronous:
State in Functional Components with Hooks (useState):
Functional components now have state thanks to the useState Hook, which was introduced with Hooks in React 16.8. You can call the useState function inside of a functional component. It gives back a two-element array:
- The value of the current state.
- A function that lets you change the value of the state.
Triggering Re-renders:
React schedules a re-render of the component and its descendants upon calling this.setState() or the state updater function given by useState. This guarantees that the modified status is reflected in the user interface.
Local Scope:
A component’s state is specific to its definition. Other components cannot directly access it or alter it. This encapsulation aids in complexity management and avoids unexpected consequences.
Initial State:
A class component’s constructor is where you specify its initial state. The initial state value is passed as a parameter to the useState() Hook for functional components that use useState.
When to Use State vs. Props:
- State: When a component has to manage and update its own data over time, use state. This data usually comes from internal logic, data collecting, or user interactions within the component.
- Props: To transfer information from a parent component to its offspring, use props. Generally speaking, child components shouldn’t alter the props they are given.
Explore all in-demand software courses at SLA.
Conclusion
This React Tutorial for Beginners covered all the fundamental concepts with examples. There is a lot more to learn for developing a React JS project. However, learn basics, JSX, components, props, state, and interactive UIs with practical experiences in our React JS course in Chennai.