I'm a bit new to React, and have been practicing by creating an application using the enums rendering method specified in this article.
However, I'm trying to apply it in a slightly different way than the article talks about, more specifically using it to conditionally render all of my website except for the <Nav />
based on the lastLinkClicked
state. I've got different page classes for each condition as listed in the WEB_PAGES object.
Maybe I'm misunderstanding this method, since I don't have much experience with enums, but my pages aren't rendering correctly. Here's my code:
class App extends Component {
constructor(props){
super(props);
this.state = {
x: ...
y: ...
z: ...
lastClickedLink: 'home' //changes to 'new', 'settings', etc. using another function not listed here
}
}
render() {
function onLinkClick(link) {
const WEB_PAGES = {
home: <Home
x={this.state.x}
/>,
new: <NewPost />,
settings: <Settings />,
signup: <SignUp />,
login: <Login />
};
return (
<div>
{WEB_PAGES.link}
</div>
);
}
return (
<div>
<Nav
y={this.state.y}
z={this.state.z}
/>
{onLinkClick(this.state.lastClickedLink)}
</div>
);
}
}
export default App;
I removed some code for brevity's sake. The error I'm getting with this setup is TypeError: Cannot read property 'state' of undefined
for home under the WEB_PAGES object.
I initially thought that this
was pointing to the WEB_PAGES object, but changing this
to App
showed that state
was undefined as well. I'm not really sure what to do at this point.
Is the enums conditional rendering method even doable on this scale? And if not, what other method would be the most ideal for this situation? Many thanks!
In javascript, When you create a function using function
keyword it creates his own new scope and also creates default object this
. So while you were trying to access this.state.x
then it will not state property inside the function. It becomes this.undefined.x
. so it is giving the error.
Whereas arrow function {(() => {})}
does not create this object but create internal scope.
try following render method in your code:
render() {
return (
<div>
<Nav
y={this.state.y}
z={this.state.z}
/>
{((link) => {
const WEB_PAGES = {
home: <Home
x={this.state.x}
/>,
new: <NewPost />,
settings: <Settings />,
signup: <SignUp />,
login: <Login />
};
return (
<div>
{WEB_PAGES[link]}
</div>
);
})(this.state.lastClickedLink)}
</div>
);
}