React Js

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

React.

js Guide: Getting Started

Introduction

React.js is a popular JavaScript library for building user interfaces, particularly single-
page applications where data changes over time. Developed by Facebook, React
enables developers to create large web applications that can update and render
efficiently in response to data changes.

Core Concepts

1. Components

Components are the building blocks of a React application. They are JavaScript
functions or classes that optionally accept inputs (called “props”) and return React
elements that describe how a section of the UI should appear.

Functional Component Example:

jsx

Copy code

import React from 'react';

function Welcome(props) {

return <h1>Hello, {props.name}</h1>;

export default Welcome;

Class Component Example:

jsx

Copy code

import React, { Component } from 'react';

class Welcome extends Component {


render() {

return <h1>Hello, {this.props.name}</h1>;

export default Welcome;

2. JSX (JavaScript XML)

JSX is a syntax extension for JavaScript that looks similar to HTML. It is used with
React to describe what the UI should look like.

Example:

jsx

Copy code

import React from 'react';

function App() {

return (

<div>

<h1>Welcome to React!</h1>

<p>This is a paragraph in JSX.</p>

</div>

);

export default App;

3. Props

Props (short for properties) are read-only attributes used to pass data from parent
components to child components.
Example:

jsx

Copy code

import React from 'react';

function Greeting(props) {

return <h1>Good {props.timeOfDay}, {props.name}!</h1>;

function App() {

return (

<div>

<Greeting timeOfDay="Morning" name="Alice" />

<Greeting timeOfDay="Evening" name="Bob" />

</div>

);

export default App;

4. State

State is used to manage data that changes over time within a component. Unlike
props, state is mutable and can be changed by the component itself.

Example:

jsx

Copy code

import React, { useState } from 'react';


function Counter() {

const [count, setCount] = useState(0);

return (

<div>

<p>You clicked {count} times</p>

<button onClick={() => setCount(count + 1)}>Click me</button>

</div>

);

export default Counter;

5. Lifecycle Methods

Lifecycle methods are hooks in class components that allow you to run code at
specific points in a component’s lifecycle, such as when it mounts or updates.

Example:

jsx

Copy code

import React, { Component } from 'react';

class MyComponent extends Component {

componentDidMount() {

console.log('Component has mounted');

}
componentDidUpdate() {

console.log('Component has updated');

render() {

return <h1>Hello World</h1>;

export default MyComponent;

Setting Up React

1. Create a React Application

The easiest way to start a new React project is by using Create React App, a
command-line tool that sets up a new React project with a sensible default
configuration.

Steps:

1. Install Create React App:

bash

Copy code

npx create-react-app my-app

2. Navigate to Your Project Directory:

bash

Copy code

cd my-app

3. Start the Development Server:

bash

Copy code
npm start

This will open your new React application in the default web browser at
http://localhost:3000.

2. Directory Structure

A typical React project has the following structure:

java

Copy code

my-app/

├── node_modules/

├── public/

│ ├── index.html

│ └── favicon.ico

├── src/

│ ├── App.js

│ ├── index.js

│ ├── components/

│ └── styles/

├── .gitignore

├── package.json

└── README.md

• public/: Contains the static HTML file and other assets.

• src/: Contains the JavaScript and CSS files. This is where you will write your
React components.

Advanced Topics

1. Handling Forms
Forms in React are controlled components, meaning that form data is handled by the
state of the component.

Example:

jsx

Copy code

import React, { useState } from 'react';

function Form() {

const [formData, setFormData] = useState({ name: '', email: '' });

const handleChange = (e) => {

const { name, value } = e.target;

setFormData({ ...formData, [name]: value });

};

const handleSubmit = (e) => {

e.preventDefault();

alert(`Name: ${formData.name}, Email: ${formData.email}`);

};

return (

<form onSubmit={handleSubmit}>

<label>

Name:

<input type="text" name="name" value={formData.name}


onChange={handleChange} />

</label>
<br />

<label>

Email:

<input type="email" name="email" value={formData.email}


onChange={handleChange} />

</label>

<br />

<button type="submit">Submit</button>

</form>

);

export default Form;

2. React Hooks

React Hooks are functions that let you use state and other React features without
writing a class. Common hooks include useState, useEffect, and useContext.

Example of useEffect:

jsx

Copy code

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

function Timer() {

const [seconds, setSeconds] = useState(0);

useEffect(() => {

const interval = setInterval(() => setSeconds(seconds + 1), 1000);

return () => clearInterval(interval); // Cleanup on component unmount


}, [seconds]);

return <h1>Time: {seconds} seconds</h1>;

export default Timer;

3. Context API

The Context API is used to pass data through the component tree without having to
pass props down manually at every level.

Example:

jsx

Copy code

import React, { createContext, useState, useContext } from 'react';

// Create Context

const ThemeContext = createContext();

// Provider Component

function ThemeProvider({ children }) {

const [theme, setTheme] = useState('light');

return (

<ThemeContext.Provider value={{ theme, setTheme }}>

{children}

</ThemeContext.Provider>

);
}

// Consumer Component

function ThemedComponent() {

const { theme, setTheme } = useContext(ThemeContext);

return (

<div>

<p>Current theme: {theme}</p>

<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>

Toggle Theme

</button>

</div>

);

// App Component

function App() {

return (

<ThemeProvider>

<ThemedComponent />

</ThemeProvider>

);

export default App;


4. Routing with React Router

React Router is a library for handling routing in React applications.

Example:

bash

Copy code

npm install react-router-dom

jsx

Copy code

import React from 'react';

import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';

function Home() {

return <h2>Home</h2>;

function About() {

return <h2>About</h2>;

function App() {

return (

<Router>

<nav>

<ul>

<li><Link to="/">Home</Link></li>

<li><Link to="/about">About</Link></li>
</ul>

</nav>

<Switch>

<Route path="/" exact component={Home} />

<Route path="/about" component={About} />

</Switch>

</Router>

);

export default App;

Best Practices

1. Component Composition

Compose components rather than inheriting them. Use small, reusable components
to build up larger components.

2. State Management

For complex state management, consider using libraries like Redux or the React
Context API.

3. Performance Optimization

Use React.memo to prevent unnecessary re-renders of functional components. Utilize


lazy loading with React.lazy and Suspense for code splitting.

4. Testing

Test components using libraries like Jest and React Testing Library to ensure your
components work as expected.

5. Code Quality
Follow consistent coding conventions and use linters (e.g., ESLint) to maintain code
quality.

You might also like