This content originally appeared on DEV Community and was authored by Tarun Gurang
Introduction
When we talk about State and Props, both are considered as variables, but they work for different tasks and purposes. To manage the structure of reacting data props can only pass it by using unidirectional from parent component to child.
What are props?
Props are defined in the parent component as variable and pass the value to the child component. Normally we familiar with C and C++ we define the variable before we must declare the variable. Same as it props are declared on one component (parent) and define in another component(child). Props follow the uni-directional flow (from parent component to child component). We can say that props are read-only components because it just assigns a value and passes the value as parameter.
How to declare props?
Here Details are child component which is imported in a parent component
<xmp><details></details>
</xmp>
Title its props attribute and my first props are props value
<xmp><details title="my first props"></details>
</xmp>
We can also pass the array as props using list
<xmp>
const value= [1, 2, 3, 4, 5];
</xmp>
<xmp><details 2="" const="" item="{[1,"></details>
</xmp>
How to pass the value?
Props are normally used for the set the internal which is based on props value which we define in constructor like that.
<xmp>
class Details extends React.Component {
constructor(props) {
super(props)
console.log(props.title)
}
}
</xmp>
We can directly assign in the render method
<xmp>
render {
return (<div><h2>Suject details:</h2>
<h2>{this.props.title}</h2></div>
)
}
</xmp>
Props never change the value it only passes the value. Props also used to allow the child component to access the method In the parent component. There is a good way to manage the state in the parent component. Every time component will display some kind of information which is based on the props.
Read More: Explain Authentication In React Application
Parent Component
<xmp>
import './App.css';
import React from 'react';
import Details from './Details';
class Footer extends React.Component
{
render()
{
var person =
{
sub1: 'Java',
sub2: 'php',
sub3:'React'
};
const value= [1, 2, 3, 4, 5];
return (<div classname="">
{/* Details component which accepts props */}<details title="my first props"></details></div>
);
}
}
export default Footer;
</xmp>
Child Component
<xmp>
import React, { } from 'react';
class Details extends React.Component
{
render()
{
Const {sub1,sub2,sub3}={...this.props};/// expmple of sperad and rest
const {a}={...this.props.item}
return(<div><h2>Suject details:</h2>
<h2>{this.props.item}</h2>
<h2>{this.props.title}</h2>
<ol><li></li><li>sub1:{sub1}</li><li></li><li>sub2:{sub2}</li><li></li><li>sub3:{sub3}</li><li></li></ol>
) }</div>
</xmp>
What is State?
The state is mange the data it can change the data while props never change the data state even set the state of data when we perform any event like button click or input change event we have to set the state of data that time state performs their task for managing the overall data.
How To Update a Component’s State?
State can not be modified directly we have to modify with a special method called setstate()
this.setState=name:’rahi’ //wrong
this.setState({name: ‘rahi’}) //right
What happens when the state changes?
The state will be changed depending on the input when the time input changes then the event will be triggered and that time state is rendered and the state collects the initial value of the state. When the state change reacts then it takes the all information immediately and re-render the DOM only which component gets an update in the state, and that’s why it react faster.
Can we use state in every component?
There are two components, one is the functional component and the second is the class component. The function is also called the stateless component because the function component is only used to define the variable work on the simple task. State is only used in the class component.
But now through the React Hooks, we can use state in function component but compatibility class component is better than function component.
What are the differences between props and state?
Props are used to pass the data while the state is used for manipulate the data and manage the data. Props only read the data while state modified the data and it's modified by its own component another component can’t be accessed by from outside. Props used attribute and value to pass the data while state used state() method.
Planning to Hire React Developer? Your Search ends here.
Full development example of props and state
<xmp>
import React, { Component } from 'react';
export default class FormDataComponent extends Component {
userData;
constructor(props) {
super(props);
this.onChangeName = this.onChangeName.bind(this);
this.onChangeEmail = this.onChangeEmail.bind(this);
this.onChangePhone = this.onChangePhone.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
name: '',
email: '',
phone: ''
}
}
// Form Events
onChangeName(e) {
this.setState({ name: e.target.value })
}
onChangeEmail(e) {
this.setState({ email: e.target.value })
}
onChangePhone(e) {
this.setState({ phone: e.target.value })
}
onSubmit(e) {
e.preventDefault()
this.setState({
name: '',
email: '',
phone: ''
})
}
// React Life Cycle
componentDidMount() {
this.userData = JSON.parse(localStorage.getItem('user'));
if (localStorage.getItem('user')) {
this.setState({
name: this.userData.name,
email: this.userData.email,
phone: this.userData.phone
})
} else {
this.setState({
name: '',
email: '',
phone: ''
})
}
}
componentWillUpdate(nextProps, nextState) {
localStorage.setItem('user', JSON.stringify(nextState));
}
render() {
return (<div classname="container"><form onsubmit="{this.onSubmit}"><div classname="form-group">
<label>Name</label>
<input classname="form-control" onchange="{this.onChangeName}" type="text" value="{this.state.name}" /></div>
<div classname="form-group">
<label>Email</label>
<input classname="form-control" onchange="{this.onChangeEmail}" type="email" value="{this.state.email}" /></div>
<div classname="form-group">
<label>Phone</label>
<input classname="form-control" onchange="{this.onChangePhone}" type="tel" value="{this.state.phone}" /></div><button classname="btn btn-primary btn-block" type="submit">Submit</button></form></div>
)
}
}
</xmp>
Conclusion
In this blog, what we have learned is about props and state with examples for each. We have also discussed the task and their purposes. How they are different from each other and in what way they are similar. We also discussed their performance and compatibility. Through this practical blog, you will get a complete idea about all these topics.
This content originally appeared on DEV Community and was authored by Tarun Gurang
Tarun Gurang | Sciencx (2021-12-15T09:08:36+00:00) A Complete Guide on React Fundamentals: Props and State. Retrieved from https://www.scien.cx/2021/12/15/a-complete-guide-on-react-fundamentals-props-and-state/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.