States and Props
What are the Props?
- In React Js data always flows unidirectionally.
- Props is a short form for properties.
- In react js props are used to pass data from one component to another.
- As react is uni directional props are passed from Parent component to child components
To learn props we have created a new component, Called garage.jsx.
function Car(props) {
return <h2>I am a { props.brand.model }!</h2>;
}
function Garage() {
const carInfo = { name: "Ford", model: "Mustang" };
return (
<>
<h1>Who lives in my garage?</h1>
<Car brand={ carInfo } />
</>
);
}
export default Garage;
What is State?
- A state is a built-in object used to manage data and contain data for components.
- A state can be defined in two ways inside "Class" and inside "Constructor"
- Example of inside the constructor:
import React, {Component} from 'react';
class Details extends React.Component {
constructor(props) {
super(props);
this.state = {
name:"Ravi",
location:"Indore"
};
}
render() {
return (
<div>
<h1>My name is {this.state.name}</h1>
<p>
I am from {this.state.location}
</p>
</div>
);
}
}
export default Details
- Example of inside the Class:
import React, {Component} from 'react';
class Details extends Component {
state = {
name:"Ravi",
location:"Indore"
};
render() {
return (
<div>
<h1>My name is {this.state.name}</h1>
<p>
I am from {this.state.location}
</p>
</div>
);
}
}
export default Details
Changing State Object
- this.setState() method is used to change a value in the state object.
- Example: Button with onClick changes its location.
import React, {Component} from 'react';
class Details extends Component {
state = {
Name: "Ravi",
location: "Indore"
};
changeLocation = () =>{
this.setState({location:"Pune"});
};
render() {
return (
<div>
<h1>My name is {this.state.Name}</h1>
<p>
I am from {this.state.location}
</p>
<button
type="button"
onClick={this.changeLocation}
>Change location</button>
</div>
);
}
}
export default Details