How to send state/props to another component in React with onClick?
The props and state are the main concepts of React. Actually, only changes in props and/ or state trigger React to rerender your components and potentially update the DOM in the browser
Props: It allows you to pass data from a parent component to a child component.
State: While props allow you to pass data from a parent component to a child component, the state is used to change the component, well, state from within. Changes to the state also trigger a UI update.
Sending state/props to another component using the onClick event: So first we store the state/props into the parent component i.e in which component where we trigger the onClick event. Then to pass the state into another component, we simply pass it as a prop. For a better understanding look at this example.
For class-based component.
App.js:
Javascript
// First Component i.e. App
import React, { Component } from
'react'
;
import
'./App.css'
import Component2 from
'./Component2'
;
class App extends Component {
state={data:
""
}
changeState = () => {
this
.setState({data:`state/props of parent component
is send by onClick event to another component`});
};
render(){
return
(
<div className=
"App"
>
<Component2 data={
this
.state.data} />
<div className=
"main-cointainer"
>
<h2>Compnent1</h2>
<button onClick={
this
.changeState} type=
"button"
>
Send state
</button>
</div>
</div>
);
}}
export
default
App;
Component2.js:
Javascript
import React from
'react'
;
const Component2 = (props) => {
return
(
<div className=
"main-cointainer"
>
<h2>Compnent2</h2>
<p>{props.data} </p>
</div>
)
}
export
default
Component2;
For Function-based component.
App.js:
Javascript
// First component i.e App
import React, { useState } from
'react'
;
import
'./App.css'
import Component2 from
'./Component2'
;
function
App() {
const [state, setstate] = useState({data:
""
})
const changeState = () => {
setstate({data:`state/props of parent component
is send by onClick event to another component`});
};
return
(
<div className=
"App"
>
<Component2 data={state.data} />
<div className=
"main-cointainer"
>
<h2>Compnent1</h2>
<button onClick={changeState} type=
"button"
>
Send state
</button>
</div>
</div>
);
}
export
default
App;
Component2.js:
Javascript
// Second Component
import React from
'react'
;
import
'./Component2.css'
export
default
function
Component2(props) {
return
(
<div className=
"main-cointainer"
>
<h2>Compnent2</h2>
<p>{props.data} </p>
</div>
)
}
Output :
Before clicking on the button:
After clicking the button:
Please Login to comment...