how to call parent componet function on button click in reactjs?

Advertisements

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

>Solution :

You can pass a callback function to Message which receives onClick and that onClick you can pass to EmbedComp and pass it as args:

CODESANDBOX

function Message({ component }) {
  const [state, setState] = useState(false);

  const showMessage = () => {
    setState(true);
  };

  return (
    <div>
      {/* CHANGE */}
      {component(showMessage)}
      {state ? <div>Message</div> : null}
    </div>
  );
}

const EmbendComp = ({ onClick }) => {
  return (
    <div className="App">
      <h1>Component</h1>
      {/* CHANGE */}
      <button onClick={onClick}>show Message</button>
    </div>
  );
};

export default function App() {
  return (
    <>
      {/* CHANGE */}
      <Message component={(onClick) => <EmbendComp onClick={onClick} />} />
    </>
  );
}

You can also pass whole component to Message and when you call it then you can pass the onClick as:

CODESANDBOX

function Message({ Component }) {
  const [state, setState] = useState(false);

  const showMessage = () => {
    setState(true);
  };

  return (
    <div>
      {/* CHANGE */}
      <Component onClick={showMessage} />
      {state ? <div>Message</div> : null}
    </div>
  );
}

const EmbendComp = ({ onClick }) => {
  return (
    <div className="App">
      <h1>Component</h1>
      {/* CHANGE */}
      <button onClick={onClick}>show Message</button>
    </div>
  );
};

export default function App() {
  return (
    <>
      {/* CHANGE */}
      <Message Component={EmbendComp} />
    </>
  );
}

Leave a ReplyCancel reply