I am trying to call parent function on button click . I am not aware how to achieve this .
parent component
export default function Message({ component }) {
const [state, setState] = useState(false);
const showMessage = ({ component }) => {
setState(true);
};
return (
<div>
{component}
{state ? <div>Message</div> : null}
</div>
);
}
now I am using this parent component .
import Message from "./message";
const EmbendComp = () => {
const onClick = () => {
alert("oooo");
};
return (
<div className="App">
<h1>Component</h1>
<button onClick={onClick}>show Message</button>
</div>
);
};
export default function App() {
return (
<>
<Message component={<EmbendComp />} />
</>
);
}
I want to call "showMessage" function on button click ..is it possible ? I want to "text" on button click..
here is my code
https://codesandbox.io/s/dazzling-gates-257xgw?file=/src/App.js:23-380
2
Answers
You can pass a callback function to
Message
which receivesonClick
and thatonClick
you can pass toEmbedComp
and pass it asargs
:CODESANDBOX
You can also pass whole component to
Message
and when you call it then you can pass theonClick
as:CODESANDBOX
You can do it by passing the parent component’s params to
component
And modify
Message
component like belowYou can try this out in this sandbox