Home > Software design >  How to pass state between functional components in a single file
How to pass state between functional components in a single file

Time:09-23

I have two functional components in a single js file. I want to pass state from one to another

    import React, { useState } from 'react';
    
    export function StepTracker(props) {
      const [steps, setSteps] = useState(0);
    
      function increment() {
        setSteps(prevState => prevState   1);
      }
    
      return (
        <div>
          Today you've taken {steps} steps!
          <br />
          <button onClick={increment}>
            I took another step
          </button>
        </div>
      );
    }

    export function funcName(props){
return(<div>{state}</div<)
}

CodePudding user response:

You can achieve this by making the other component a child component for the one holding the state.

import React, { useState } from 'react';
import './style.css';

export default function StepTracker() {
  const [steps, setSteps] = useState(0);

  function increment() {
    setSteps((prevState) => prevState   1);
  }

  return (
    <div>
      <FuncName state={steps} />
      Today you've taken {steps} steps!
      <br />
      <button onClick={increment}>I took another step</button>
    </div>
  );
}

export function FuncName(props) {
  return <div>{props.state}</div>;
}

Another method is to use context. Here's a guide on the official React documentation.

CodePudding user response:

You can do this by

   
   export function StepTracker(props) {
     const [steps, setSteps] = useState(0);
   
     function increment() {
       setSteps(prevState => prevState   1);
     }
   
     return (
       <div>
         Today you've taken {steps} steps!
         <br />
         <button onClick={increment}>
           I took another step
         </button>
   <FuncName steps={steps}/>
       </div>
     );
   }

   export function FuncName(props){
return(<div>{state}</div<)
}
  • Related