What is State in React?
State of a component is an object that holds some information that may change over the lifetime of the component. The important point is whenever the state object changes, the component re-render
Lets take an example of User component with message state.
Here useState hook has been used to add state to the User component and it return array with current state and
function to update it.
Declare state in the function component
import React ,{useState} from "react";function User(){
const [message,setMessage]=useState("welcome to React world");
return(
<h1>{message}<h1/>
);
}
Declare state in the class component
class User extends React component {
constructor (props){
supper(props);
this state={
message:"welcome to React world",
};
}
render(){
return(
<h1>{this.state.message}<h1/>
);
}
}
State is similar to props,but it is private and fully controlled by the component. It is not accessible to any other component till the owner component decides to pass it.
What is Props in React
Props are input to Component. It can be single value or objects, containing a set of values that are passed to
components on creation, similar to HTML tag attributes.
The primary purpose of props in React is to provide following component functionality.
- Pass custom data to your component
- Trigger state changes
This reactProps(or whatever you come up with) attributes name then becomes a property attached to React's native
"props"
object which originally already exists on all components created using React library
//props.reactProps
Functional Component
import ReactDom from "react-dom";
const ChildComponent =(props)=>{
return(
<div>
<p>{props.name}</p>
<p>{props.age}</p>
</div>
);
};
const ParentComponent =(props)=>{
return(
<div>
<ChildComponent name="jo" age="30"/>
<ChildComponent name="So" age="29"/>
</div>
);
};
Class Component
import ReactDom from "react-dom";
class ChildComponent extends React.Component{
render(){
return(
<div>
<p>{this.props.name}</p>
<p>{this.props.age}</p>
</div>
);
}
}
No comments:
Post a Comment