REACT PROPS, STATE AND ROUTER

 

React Props and State

React Props

Props (short for properties) are used to pass data from a parent component to a child component. They are immutable and allow you to configure components.


Definition:

  • Characteristics: Immutable, passed from parent to child.

Passing Variables:

function Greeting(props) {
return <h1>Hello, {props.name}!</h1>; } // Usage <Greeting name="Alice" />

Output: Displays "Hello, Alice!"

Passing Parameters:

function UserProfile({ name, age }) {
return <p>{name} is {age} years old.</p>; } // Usage <UserProfile name="Bob" age={30} />

Output: Displays "Bob is 30 years old."

Using Objects:

function Address({ address }) {
return <p>{address.street}, {address.city}</p>; } // Usage <Address address={{ street: "123 Main St", city: "Anytown" }} />

Output: Displays "123 Main St, Anytown."

React State

State is used to manage data that changes over time within a component. Unlike props, state is mutable and managed within the component.


Definition:

  • Characteristics: Mutable, managed within the component.

Example:

class Counter extends React.Component {
constructor(props) { super(props); this.state = { count: 0 }; } increment = () => { this.setState({ count: this.state.count + 1 }); }; render() { return ( <div> <p>Count: {this.state.count}</p> <button onClick={this.increment}>Increment</button> </div> ); } }

Output: Displays a counter with a button that increments the count.

State vs Props:


  • Props: Used to pass data and event handlers down to child components. Immutable and managed by the parent component.
  • State: Used to manage data within the component. Mutable and managed by the component itself.

React Router

React Router is a library for routing in React applications. It enables navigation between different components and pages without reloading the browser.


Installation:

npm install react-router-dom

Setting Up Environment:

  1. Import Router Components:

    import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
  2. Set Up Routes:

    function App() {
    return ( <Router> <div> <nav> <ul> <li><Link to="/">Home</Link></li> <li><Link to="/about">About</Link></li> </ul> </nav> <Switch> <Route path="/about"> <About /> </Route> <Route path="/"> <Home /> </Route> </Switch> </div> </Router> ); } function Home() { return <h2>Home Page</h2>; } function About() { return <h2>About Page</h2>; }

Output:

  • Home Page and About Page are displayed based on the URL route, with navigation links allowing switching between them.

Post a Comment

0 Comments