Search code examples
javascriptreactjsreact-hooksrendering

How to let values as it is when conditionally rendering from one component to another


I am condinitionally rendering two componenets with the same route. First components has two input field and one next button. After pressing the next button I am rendering to the next page. But when clicking on the back button how can I get the that I have entered earlier. I am using useRef() but when I am coming to the first page again then all the data that I have entered are not present. So how can I set the data as it is while I am conditionally rendering between two components

I have tried with the useRef() but the entered values are not there when I am pressing the back button and reaching to that first component again.


Solution

  • That is happening because your input data is not stored. As soon as component is unmounted from the page all of its data is lost, unless you store it outside this component. There are two main ways to do it in react: component local state and state libraries (redux or mobx);

    React documentation has a great article on state management.

    In your case the easiest solution would be to create state hooks inside container component, where your conditional rendering takes place, and pass this state and modification functions to each component that contains your inputs:

    export const Routing = () => {
      const [firstInput, setFirstInput] = useState('');
      const [secondInput, setSecondInput] = useState('');
      const [stage, setStage] = useState(0);
    
      if (stage === 0) {
        return <FirstComponent inputValue={firstInput} onInputChange={setFirstInput} />
      }
    
      if (stage === 1) {
        return <SecondComponent inputValue={secondInput} onInputChange={setSecondValue} />
      }
    }
    

    This is approach is fine for small scale situations like this, when your application starts growing, different modules start to use the same state logic. They often times need to use the same values and modify it. In this point managing this state tree becomes very complicated. Especially passing state as props to the whole children components chain. That is where aforementioned libraries come in handy. They move app state management in a separate module and provide a way for all modules to access it and modify.

    React also has a way of organizing large scale state modules: Context API and useReducer hook, you can read about it in official docs