Day 5: Props and State in React
Dhaval Patel
Posted on March 1, 2024
Introduction
Welcome to Day 5 of our 30-day blog series on React.js! Today, we'll explore two essential concepts in React: props and state. Props allow us to pass data from parent to child components, while state enables components to manage their internal data and re-render when necessary.
Props in React
Props (short for properties) are a mechanism for passing data from parent to child components in React. Props are read-only, meaning that child components cannot modify the props passed to them by their parent components.
Here's an example of how props are used in React components:
// Parent Component
function ParentComponent() {
return <ChildComponent name="John" age={30} />;
}
// Child Component
function ChildComponent(props) {
return (
<div>
<p>Name: {props.name}</p>
<p>Age: {props.age}</p>
</div>
);
}
In the above example:
The ParentComponent renders the ChildComponent and passes it props such as name and age.
The ChildComponent receives props as an argument and accesses them using dot notation (props.name,
props.age
).
State in React
State is a built-in feature in React that allows components to manage their internal data. Unlike props, which are passed from parent to child, state is managed locally within the component and can be updated using the setState
method.
Here's an example of how state is used in React components:
// Class Component with State
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Increment
</button>
</div>
);
}
}
In the above example:
The
Counter
component has an internal statecount
, initialized to 0.The
render
method displays the current count and a button to increment the count.When the button is clicked, the
setState
method updates the state, triggering a re-render of the component.
Props and state are two fundamental concepts in React that enable components to communicate with each other and manage their internal data. Props allow data to flow from parent to child components, while state enables components to manage their internal state and respond to user interactions.
Stay tuned for tomorrow's post, where we'll dive deeper into handling events in React components and implementing interactivity in our applications.
Posted on March 1, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.