new to nextjs (and react), i am trying to change the state of component from outside of component,
basically i am conditionally rendering html in component, and i have one button in component which calls a function, and set the isSubmitted = true
now if isSubmitted is true render the submitted component, if false then render button component
and we can’t use hooks outside the component!?
is there any way we can do this without hooks?
sample code:
let isSubmitted = false;
export default function ConditionalRenderingExample() {
<>
{ (isSubmitted) && <h1> submitted</h1>}
{ (!isSubmitted) && <button onClick{()=>submitFunction()} > submit </button>}
</>
}
function submitFunction(){
isSubmitted = true;
}
3
Answers
It is recommended use
useState
for state changes in react instead of the way you are using it. You can use it like below,In the
submitFunction()
use can set the state like below,The two things you mentioned are invalid in React,
If the state lives only inside this component, i.e. it will be used and changed only here, use
useState
You have to either pass in the state you would like to change as props into the component and update that variable in another component if it will be changed outside of this component,
or use a state management library, I would recommend you start with React Context as a starting point if that’s what you are looking for
Tutorial reference: https://react.dev/learn/sharing-state-between-components
First of all, I would consider changing a component’s state from the outside to be an antipattern.
So if you encounter a situation like that I would question the approach. Maybe there is another way of doing it?
Regarding your example I think there is a nice way of handling it:
In the end, the parent component can look something like this: