What is De-Structuring props and state?
Destructuring is a characterstic of javascript. it is used to take out section of data from an array or object,we can assign them to new own variable created by the developer.
In does not change an array or any object, it makes a copy of the desired object or array element by assigning them in its own new variable,later we use this in react.
Destructuring with props
Destructuring props in function component
We can destruct the prop data and store in name or age variable.and we can directly use name and age in component.
Always remember our variable name is same as props name otherwise it show errors.
FIRST WAY:-
import React from 'react'
function User({name, age}) {
return (
<div>
<h1>{name}</h1>
<h1>{age}</h1>
</div>
)
}
export default User;
SECOND WAY:-
In these way we can create new variable component before return and assign props init.
import React from 'react'
function User(props) {
const {name, age} = props
return (
<div>
<h1>{name}</h1>
<h1>{age}</h1>
</div>
)
}
export default User;
Destructuring props in class component
import React, { Component } from 'react'
export default class User extends Component {
render() {
const {name, age} = this.props
return (
<div>
<h1>{name}</h1>
<h1>{age}</h1>
</div>
)
}
}
Destructuring with state
Destructuring state with class component
import React, { Component } from 'react'
export default class User extends Component {
constructor(){
super()
this.state = {
name:"ankuda",
age:23
}
}
render() {
const {name, age} = this.state
return (
<div>
<h1>{name}</h1>
<h1>{age}</h1>
</div>
)
}
}