What is reactJS props?
“props” is a special keyword in React, which stands for “properties” and is being used for passing data from one component to another. But the important part here is that data with props are being passed in a uni-directional flow, means it can’t modify by child component. Props data is available for read only to child component.
let’s see how to pass Props in function component
import ‘./App.css’
class App extends Component {
render(){
return (<div className=”App”>
<PropsFunction title=”Reactjs Props Example” author=”sisnolabs” />
</div>);
}
}
const PropsFunction = (props) => {
return(<div>
<h1>{props.title}</h1>by {props.author}
</div>);
}
export default App;
let’s see how to pass Props in class component
import ‘./App.css’
class App extends Component {
render(){
return (<div className=”App”>
<PropsClass title=”Reactjs Props Example” author=”sisnolabs” />
</div>);
}
}
class PropsClass extends Component {
render(){
return(<div>
<h1>{this.props.title} </h1>by {this.props.author}
</div>)
}
}
export default App;
Destructuring props
You can also access the props by creating the const inside the function, it is called destructuring props. Please see the below child function. Same like you used in class component but you must use the this.props in place of props.
const {title, author} = props
return(<>
<h1>{title}</h1>by {author}
</>);
}
What is reactJS state
As we saw the props, which can’t be modified by the component. But state allowed component to manage it’s own data.
let’s see how to use state in class component
import ‘./App.css’
class App extends Component {
render(){
return (<div className=”App”>
<PropsClass />
</div>);
}
}
class PropsClass extends Component {
constructor() {
this.state = {
title: ‘Reactjs State Example’,
author: “Sisnolabs”
};
}
render() {
return (<div>
<p>{this.state.title}</p>
<p>{this.state.author}</p>
</div>);
}
}
export default App;
In function component creating & accessing the state is different. You must use “useState” hook to create the object in function component.
let’s see how to use “useState” hook in function component
import ‘./App.css’
class App extends Component {
render(){
return (<div className=”App”>
<PropsFunction />
</div>);
}
}
const PropsFunction = () =>{
const [count, setCount] = useState(0);
return(<div>
<button onClick={()=>setCount(count + 1)}>You Clicked {count} times</button>
</div>)
}
export default App;
Difference between state and props
- Props are variables passed to the component from parent to child component.
- Props can not be changed by child component.
- Access the props in component:
Props.propsName in function component
this.props.propsName in class component
- State manage inside the component.
- Class have full permission to modify the state
- Access the state in component:
useState hook used to create the state in function component
this.state used to create in class component