Any Way to Pass Data from Sibling Components

In the following code, I’m wanting to pass information from my Break and Session components to my main Timer component. Athough I know they are siblings, I’m not sure how to pass info from one another. Any direction you can point me to?

const { useState } = React
const App = () => {
  return (
  <div>
    <SessionTime />
    <BreakTime />
    <Timer />
    </div>
  )
}

const SessionTime = () => {
  const [sessionTime, setSessionTime] = useState(25)
  return (
  <div>
      <h1 id="session-label">Session</h1>
      <h2 id="session-length">{sessionTime}</h2> 
      <button id="session-increment" onClick={() => setSessionTime(sessionTime + 1)}>+</button>
      <button id="session-decrement" onClick={() => setSessionTime(sessionTime - 1)}>-</button>
   </div>
  )
}

const BreakTime = () => {
  const [breakTime, setBreakTime] = useState(5)
  return (
  <div>
      <h1 id="break-label">Break Length</h1>
      <h2 id="berak-length">{breakTime}</h2>
      <button id="break-increment" onClick={() => setBreakTime(breakTime + 1)}>+</button>
      <button id="break-decrement" onClick={() => setBreakTime(breakTime - 1)}>-</button>
   </div>
  )
}

const Timer = () => {
   const [totalTime, setTotalTime] = useState('')
  return (
  <div> {/*Change text to Session or Break whenever necessary*/}    
      <h2 id="timer-label">Session</h2>
      <h3 id="time-left">MINUTES : SECONDS</h3>
      <button id="start-stop">Start/Stop</button>
      <button id="start-stop">Reset</button>  {/*US 11*/}          
   </div>
  )
}

ReactDOM.render(<App />, document.getElementById('root'))  

Unless you have a state management tool like Redux or are using something like context API, you need to do this the “old-fashioned” way, pass it up to the nearest common ancestor. Passing down is easy - passing up means the parent passes a callback down to its descendants that they can use to change the ascendants state. I once did this pen as an example.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.