Open In App

Getting Started with React

ReactJS, often referred to as React, is a popular JavaScript library developed by Facebook for building user interfaces. It emphasizes a component-based architecture, where UIs are built using reusable components. React uses a declarative syntax to describe how UIs should look based on their state, simplifying development and enhancing code readability.

React also utilizes a virtual DOM to optimize rendering performance by minimizing actual DOM manipulations. React's unidirectional data flow and rich ecosystem of libraries and tools have made it a go-to choice for frontend development, especially in building single-page applications (SPAs).

Why ReactJS ?

ReactJS, commonly known as React, is a JavaScript library developed by Facebook for building robust user interfaces. Here's why React has become immensely popular among developers:

Setting Up Your Development Environment:

npx create-react-app my-react-app

Screenshot-2024-03-16-143854

Step 2: Once the project is created, navigate to your project directory:

cd my-react-app

Step 3: Start the development server to see your React application in action:

npm start

Screenshot-2024-03-16-144231

Understanding React Components

Creating Your First React Component:

In React, components are the building blocks of UIs. You can create a new component by defining a JavaScript function or class. Here's an example of a simple functional component in React:

import React from 'react';

const MyComponent = () => {
  return <div>Hello, React!</div>;
};

export default MyComponent;

JSX (JavaScript XML)

JSX allows you to write HTML-like code within JavaScript. It's a syntax extension that makes React's component structure more readable and expressive.

const element = <h1>Hello, JSX!</h1>;

Working with Props and State:

Props (short for properties) and state are two fundamental concepts in React. Props are used to pass data from parent to child components, while state is used to manage component-specific data. Here's an example of how to use props and state in a React component.

Example: This example shows the use of props and state.

import React, { useState } from 'react';

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

export default Counter;

Handling Events:

In React, you can handle user events like clicks and input changes using event handlers. Event handlers are functions that are called when a specific event occurs.

This code snippet demonstrates event handling in React using an 'onClick' attribute that references the 'handleClick' function, triggering an alert when the button is clicked.

Example: This example shows the use of handling events.

import React from 'react';

function Button() {
  function handleClick() {
    alert('Button clicked!');
  }

  return <button onClick={handleClick}>Click Me</button>;
}

export default Button;

Conditional Rendering:

React allows you to conditionally render components based on certain conditions. You can use JavaScript's conditional operators like if statements and ternary operators to conditionally render components.

The code uses conditional rendering in React to display "Welcome back!" if the user is logged in (true), and "Please log in." if the user is not logged in (false).

Example: This example shows the use of conditional rendering.

import React from 'react';

function Greeting({ isLoggedIn }) {
  return isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please log in.</h1>;
}

export default Greeting;

Lists and Keys:

When rendering lists of items in React, each item should have a unique key prop to help React identify which items have changed, added, or removed. Keys should be stable, predictable, and unique among siblings.

The 'key' attribute is used on each '<li>' element to uniquely identify and optimize rendering when working with lists in React.

Example: This example shows the use of lists and keys.

import React from 'react';

function TodoList({ todos }) {
  return (
    <ul>
      {todos.map(todo => (
        <li key={todo.id}>{todo.text}</li>
      ))}
    </ul>
  );
}

export default TodoList;

Styling React Components:

React allows you to style components using CSS, inline styles, or CSS-in-JS libraries like styled-components. You can use the style prop to apply inline styles to components. Here's an example of styling a component with inline styles.

Example: This example shows the styling the react component.

import React from 'react';

function StyledComponent() {
  const styles = {
    backgroundColor: 'lightblue',
    padding: '10px',
    borderRadius: '5px'
  };

  return <div style={styles}>Styled Component</div>;
}

export default StyledComponent;

Introduction to React Hooks:

React Hooks are functions that allow functional components to use state and other React features without writing a class. They were introduced in React 16.8 to address common issues with class components, such as managing state and lifecycle methods.

Example: Here's an example of using the useState hook in a functional component:

import React, { useState } from 'react';

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

export default Counter;

Building a Simple React Application:

Now that you have a basic understanding of React, it's time to build a simple React application. You can start by creating a project structure, defining components, managing state, and adding interactivity to your application. Here's a simple example of a React application:

/* index.css */

body {
    display: flex;
    justify-content: center;
    align-items: center;
}

button {
    margin: 10px;
}

p,
h2 {
    text-align: center;
}
import React, { useState } from 'react';

const Counter = () => {
  // State to hold the count value
  const [count, setCount] = useState(0);

  // Function to increment the count
  const incrementCount = () => {
    setCount(count + 1);
  };

  // Function to decrement the count
  const decrementCount = () => {
    setCount(count - 1);
  };

  return (
    <div>
      <h2>Counter</h2>
      <p>{count}</p>
      <button onClick={incrementCount}>
        Increment
      </button>
      <button onClick={decrementCount}>
        Decrement
      </button>
    </div>
  );
};

export default Counter;

Output:

der

Component Lifecycle:

Example: This example shows the use of all component lifecycle methods in one code example.

import React, { Component } from 'react';

class LifecycleExample extends Component {
    constructor(props) {
        super(props);
        this.state = { count: 0 };
        console.log('Constructor called');
    }

    componentDidMount() {
        console.log('Component did mount');
    }

    componentDidUpdate() {
        console.log('Component did update');
    }

    componentWillUnmount() {
        console.log('Component will unmount');
    }

    handleIncrement = () => {
        this.setState(
            (prevState) => ({ count: prevState.count + 1 }));
    };

    render() {
        console.log('Render method called');
        return (
            <div>
                <h1>Lifecycle Example</h1>
                <p>Count: {this.state.count}</p>
                <button onClick={this.handleIncrement}>
                    Increment
                </button>
            </div>
        );
    }
}

export default LifecycleExample;

Output:

cde

React Router:

React Router is a library that enables routing in React applications, allowing you to define routes and navigate between different views or pages within a single-page application (SPA). You can install React Router using npm or yarn:

npm install react-router-dom
# or
yarn add react-router-dom

Note: React Router provides components like BrowserRouter, Route, and Link for setting up routing in your application.

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

const Home = () => <h1>Home Page</h1>;
const About = () => <h1>About Page</h1>;

const App = () => (
    <Router>
        <nav>
            <Link to="/">Home</Link>
            <Link to="/about">About</Link>
        </nav>
        <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/about" element={<About />} />
        </Routes>
    </Router>
);

export default App;

Output:

csw

Managing State with Context API:

The Context API in React provides a way to share state across the component tree without having to pass props manually at every level. It's particularly useful for managing global state, such as user authentication, theme preferences, or language settings.

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

// Create a context with initial state
const MyContext = createContext({
data: null,
updateData: () => { },
});

const MyProvider = ({ children }) => {
const [data, setData] = useState(null);

const updateData = newData => {
setData(newData);
};

return (
<MyContext.Provider value={{ data, updateData }}>
{children}
</MyContext.Provider>
);
};

export { MyContext, MyProvider };
Article Tags :