Reputation: 217
I'm a beginner at react hooks and I am trying to assign a state to every page of my module and set the initial state to an intro page and change state (page) on clicking next button.
This is how my main payment page looks
const [portalStage, setPortalStage] = useState("INTRO");
const Screens = {
INTRO: <IntroScreen />,
Post_INTRO: <Payment />, }
useEffect(() => {
setScreen();
}, [context]);
const setScreen = async () => {
setPortalStage("Post_INTRO");
}
{Screens[portalStage]}
<IntroScreen onClick = {setScreen} />
Now I am trying to add an Intro page to it which should always open first and then on clicking the next button on the introscreen it should redirect to the main component.
const IntroScreen = () => {
return (
<Wrapper>
<Content>
<h1>Coupons only!</h1>
<p>Increase your eligibility limit today!</p>
<Button>
Next
</Button>
</Content>
</Wrapper>
);
};
export default IntroScreen;
With this approach I can only see the main page and not the introscreen. What am I doing wrong in assigning state to both screens
Upvotes: 0
Views: 1509
Reputation: 329
A clean way to do this if you dont want use different routes would be to re-render when the next button is clicked. Some thing like below:
MainPaymentPage.js
const MainPaymentPage =(props)=>{
const [isNextClicked,setNextClicked]=useState(false);
let componentCode=<IntroScreen click={()=>setNextClicked(true)}/>
if(isNextClicked){
componentCode=<Payment/>
}
return(
{componentCode}
)
}
export default MainPaymentPage;
and add a click listener in your IntroScreen component like below:
const IntroScreen = (props) => {
return (
<Wrapper>
<Content>
<h1>Coupons only!</h1>
<p>Increase your eligibility limit today!</p>
<Button onClick={props.click}>
Next
</Button>
</Content>
</Wrapper>
);
};
export default IntroScreen;
you will have to make a similar change in your button component so that it can handle the click event. If the Button component comes from a framework like MaterialUI or Bootstrap, it should be able to handle it on its own, but you might have to rename the listener from onClick to whatever your framework wants.
The way the above code works is that there is now a parent component which has a state deciding which component to display based on the state value(isNextClicked, in this case). Initially, it will be set to false, causing the componentCode variable to be set to the code for IntroScreen. When the next button is clicked in the intro screen, it will change the state of the parent component(MainPaymentPage, in this case) to true, causing a re-render. This time, since isNextClicked is true, componentCode will be set to the code for your Payment component.
Upvotes: 1