0

I have a React Typescript functional component like below,

const Comp = (): JSX.Element => {
  const [showNext, setShowNext] = useState(false);
  const [data1, setData1] = useState(array);

  return showNext ? <AnotherComponent /> : <></>;
};

If I move to the next component and coming back to the previous one, then state values are gone in the previous component. So, in UI already entered inputs are gone. How can I avoid this, or how can I store it?

2
  • Don't unmount the component, hide it Commented Sep 7, 2021 at 9:54
  • To expand on the comment above, passing in a visible property and letting the component handle hiding itself is a pretty common approach. Commented Sep 7, 2021 at 9:58

1 Answer 1

2

By using conditional rendering you unmount the component depending on the state, unmounting component loses its state.

Therefore try hiding it with CSS or save its state in the parent component (Comp in this case)

// Save state in parent
const Comp = () => {
  const [nextState, setNextState] = useState({})

  return showNext ? <AnotherComponent {...nextState}/> : <></>;
};

// Or hide it with CSS
const Comp = () => {
  const [nextState, setNextState] = useState({})

  return <AnotherComponent className={showNext ? 'myClassName' : 'hideClass'} />;
};

// Possible CSS
.hideClass {
  display: none;
}

.myClassName{
  display: block;
}
Sign up to request clarification or add additional context in comments.

1 Comment

hiding class helps me. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.