DEV Community

Cover image for Props and State with example
Anil
Anil

Posted on • Updated on

Props and State with example

In React, props and state are fundamental concepts used to manage data and pass it between components. Here's an explanation of each along with examples:

1. Props:

  • Props (short for properties) are used for passing data from parent to child components in React.
  • Props are read-only and cannot be modified by the child component.
  • They are passed as attributes to a component and can be accessed using this.props within the component.

Example:

// `ParentComponent.js`
import React from 'react';
import ChildComponent from './ChildComponent';

class ParentComponent extends React.Component {
  render() {
    return <ChildComponent name="John" age={25} />;
  }
}

export default ParentComponent;

Enter fullscreen mode Exit fullscreen mode
// `ChildComponent.js`
import React from 'react';

class ChildComponent extends React.Component {
  render() {
    return (
      <div>
        <p>Name: {this.props.name}</p>
        <p>Age: {this.props.age}</p>
      </div>
    );
  }
}

export default ChildComponent;

Enter fullscreen mode Exit fullscreen mode

2. State:

  • State is used to manage data within a component.
  • It is mutable and can be updated using this.setState() method provided by React.
  • State is initialized in the constructor of the component and can be accessed using this.state.

Example:

import React from 'react';

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  incrementCount = () => {
    this.setState({ count: this.state.count + 1 });
  }

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.incrementCount}>Increment</button>
      </div>
    );
  }
}

export default Counter;


Enter fullscreen mode Exit fullscreen mode

In the example above, ParentComponent passes name and age as props to ChildComponent. In ChildComponent, these props are accessed using this.props.name and this.props.age.

In the Counter component example, count is managed as state using this.state.count. The incrementCount method updates the count when the button is clicked using this.setState().

github
website

Array methods in react.js
Fragment in react.js
Conditional rendering in react.js
Children component in react.js
use of Async/Await in react.js
Array methods in react.js
JSX in react.js
Event Handling in react.js
Arrow function in react.js
Virtual DOM in react.js
React map() in react.js
How to create dark mode in react.js
How to use of Props in react.js
Class component and Functional component
How to use of Router in react.js
All React hooks explain
CSS box model
How to make portfolio nav-bar in react.js

Top comments (1)

Collapse
 
shan010101 profile image
shan

Thank's for your share