Home > Software design >  Getting data from react state function component
Getting data from react state function component

Time:04-05

I have 2 function component , one have input and button and its passing data to states. Now i want to get state data from first function conlmponent to second component and display text to my div in second component. Is it possible to share states data from 1st component to 2nd component? The component are functions not classes

function Articles(){
  return(<div>
    <h1>{inputtext}</h1>
  </div>)
}

function Inputform() {
  const [inputtext, setInputtext] = useState('');
  const [task_list,setTask_list] = useState([]);

  function changer(event){
    setInputtext(event.target.value);
  }
  function add_post(){
    setTask_list(inputtext);
  }

  return (
    <div>
    <label>Post</label>
    <input name="first" onChange={changer} />
    <button onClick={add_post}>Dodaj</button>
    </div>
  )
}

trying to get states in Articles from Input but it doesnt work

CodePudding user response:

State belongs to a component. It does not create global variables.

If you want to pass data from a state to another component, then:

  • The recipient must be a child of the element holding the data
  • You can pass it as a prop

Since you don't have <Article propName={stateVariable} /> you can't do that.


If the destination isn't a child of the element holding the state then you need to Lift State Up.

  1. Move the useState hook to component that is ancestor of both <Article> and <Inputform>
  2. Pass the set function as a prop to <Inputform>
  3. Pass the state value variable as a prop to <Article>.

For complex systems where the common ancestor is a long way from the components that need to work with the state, you might consider using Context or an external state management system like Redux.

CodePudding user response:

what you would like to do, is to put this two components inside a third one and have them share whatever states/data you want.

function ThirdComponent() {
    const [inputtext, setInputtext] = useState('');
    const [task_list,setTask_list] = useState([]);

    function Articles(){
      return(<div>
       <h1>{inputtext}</h1>
      </div>)
    }
    function Inputform() {
      
      function changer(event){
        setInputtext(event.target.value);
      }
      function add_post(){
        setTask_list(inputtext);
      }

      return (
        <div>
           <label>Post</label>
           <input name="first" onChange={changer} />
           <button onClick={add_post}>Dodaj</button>
        </div>
     )
    }
    return (
        <>
        </>
    ) 
}
  • Related