Ojay
Ojay

Reputation: 703

Trigger a function in another component on click a button from a different component in React

I am trying to trigger a start function in a different componentB when I click the start button in componentA

Note: Both components are neither parent to child components

Component A

import React from "react"

function ComponentA(props) {        
  return (
    <div>
      <button>Start</button>
    </div>
  )
}

export default ComponentA; 

Component B

import React from "react";

function ComponentB(props) {
  const [isStarted, setStarted] = React.useState(false);

  const start = () => setStarted(true);

  return <div>{isStarted ? "Starting..." : "Not Starting.."}</div>;
}

export default ComponentB;

Upvotes: 1

Views: 5587

Answers (1)

BeFoRE
BeFoRE

Reputation: 118

One way you could do it is by creating a callback prop on ComponentA, changing the state of the parent component of ComponentA and passing it to ComponentB via a prop and capture that prop change with a useEffect.

Example:

Parent

function Parent(){
  const [started, setStarted] = useState(false)

  return(
    <div>
      <ComponentA onClick={() => setStarted(true)}/>
      <ComponentB started={started}/>
    </div>
  )
}

ComponentA

function ComponentA({onClick}){
  return(
    <div>
      <button onClick={() => onClick()}/>
    </div>
  )
}

ComponentB

function ComponentB({started}) {
  const [isStarted, setStarted] = React.useState(started);

  useEffect(() => {
    setStarted(started)
  }, [started])

  return <div>{isStarted ? "Starting..." : "Not Starting.."}</div>;
}

Another way would be using useContext:

https://reactjs.org/docs/hooks-reference.html#usecontext

https://reactjs.org/docs/context.html

Honestly, I am a bit lazy to also include an example which is in my opinion worse. Here is an example that uses useContext that might be useful. https://stackoverflow.com/a/54738889/7491597

Upvotes: 2

Related Questions