1

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;
Ojay
  • 663
  • 2
  • 9
  • 21

1 Answers1

1

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

BeFoRE
  • 98
  • 6
  • Please how do I make use of the useContext? – Ojay Nov 01 '20 at 13:08
  • I advise against using useContext everywhere in your app, especially when only one component needs information from another (which is in your case). useContext should really only be used if multiple components need the same application wide data. That being said you can find the documentation here: https://reactjs.org/docs/context.html – BeFoRE Nov 01 '20 at 13:23
  • Ok, please can you show a quick demo using my question above? – Ojay Nov 01 '20 at 13:26
  • I'm just learning react/nextjs too and I was looking for the same solution, found this thread and did @BeFoRE 's 1st recommendation and it worked first try. I even passed "started" from componentB to a child component under componentB and it worked, so stoked! – RobbieC Mar 18 '22 at 01:54