On page load I want React to render a component randomly because I have two different survey forms that I want randomly assigned to a user. However, because of the multiple re-renders that react goes through the piece of code doesn’t quite work the way I expected.
Sometimes, depending on the randomness, <OpenSurvey />
will render first, then you’ll see it briefly and it will switch to <ClosedSurvey />
.
How do I handle this so that my RandomlyAssignSurvey function only renders once? Do I even need the useEffect hook there?
JavaScript
x
37
37
1
const SurveyPage = (props) => {
2
3
useEffect( () => {
4
RandomlyAssignSurvey()
5
},[])
6
7
const RandomlyAssignSurvey = () => {
8
let openSurvey = "OpenSurvey"
9
let closedSurvey = "ClosedSurvey"
10
const pages = [openSurvey, closedSurvey]
11
let page = pages[Math.floor(Math.random() * pages.length)];
12
13
console.log(page)
14
if (page === "OpenSurvey") {
15
return (
16
<OpenSurvey/>
17
)
18
} else {
19
return (
20
<ClosedSurvey/>
21
)
22
}
23
}
24
25
return (
26
<SceneContainer
27
render={() => (
28
<SurveyContainer>
29
{RandomlyAssignSurvey()}
30
</SurveyContainer>
31
)}
32
/>
33
);
34
};```
35
36
37
Advertisement
Answer
Not sure what your render
prop is doing, but an easier approach to simply rendering a random component might look like this.
JavaScript
1
6
1
const SurveyPage = () => {
2
return (
3
Date.now()%2 === 1 ? <OpenSurvey/> : <ClosedSurvey/>
4
);
5
};
6