In my project I have two components, one is App.js that is Parent component, and another one is Child.js this is Child component.
Now In Child.js component I have one button, I have written some code to change background color and text color of Child.js component button. And it's working fine.
Now What I am thinking is In Child.js component before I am clicking the button, the button background color is Yellow and text color is white. Now if I click the button, now the button background color and text color is changed.
Now I have to pass the updated state of the child component to App.js component.
I have to pass an onClick function from child to Parent only when I click the Child component.
This is my code
This is App.js
import React, { useState } from 'react';
import './App.css';
import Child from './Child/Child';
const App = () => {
return (
<div>
<button className='btn btn-danger'>Parent button</button>
<Child></Child>
</div>
)
}
export default App
This is Child.js
import React, { useState } from 'react';
import './Child.css';
const Child = () => {
const [color, setColor] = useState('yellow');
const [textColor, setTextColor] = useState('white');
return (
<div>
<button className='btn btn-primary mt-5' style={{ background: color, color: textColor }}
onClick={() => { setColor("black"); setTextColor('red') }}
>Child Button</button>
</div>
)
}
export default Child
If you feel I am not clear with my doubt please put a comment.