I hope this question isn't too subjective. I've been doing a lot of React development lately, and I have a header that used to have two different renderings.
Recently my client has asked for two additional renderings. I could nest conditionals in the renderings, but this feels messy to me and against good practices.
For example I have this:
{this.state.headerLoc ? (
<div className="secondary-nav">
...
</div>
) : (
<Back />
)}
I'd like to add two additional conditions to this - is there a "clean" way to do this without a bunch of additional nesting? Would refactoring/subcomponents be the only way to handle this condition?
EDIT: Pseudo-code example of what I want to do:
render {
if(page == 'page1') {
<renderX />
}
else if(page == 'page2') {
<renderX2 />
}
else if(page == 'page3') {
<renderX3 />
}
else if(page == 'page4') {
<renderX4 />
}
}
EDIT: Update for what I am doing now:
const HeaderArrays = {
FrontPage: ["/"],
SearchPage: ["cards", "map", "detail"],
NonSearchPage:[],
NonSearchPageHamburger:["settings"],
}
HeaderComponents() {
var routerPath = this.props.router.location.pathname;
for (const component in HeaderArrays) {
const value = HeaderArrays[component];
if(HeaderArrays[component].includes(routerPath)) {
return component;
}
return "FrontPage";
}
render() {
const ComponentToRender = this.HeaderComponents();
return(
<ComponentToRender />
You can just map components to a key in an object. this way you can omit a bunch of if else statements
const HeaderComponents = {
page1: Page1HeaderComponent,
page2: Page2HeaderComponent,
page3: Page3HeaderComponent,
page4: Page4HeaderComponent
}
and usage would be
render() {
const { page } = this.props // assuming page comes from props
const ComponentToRender = HeaderComponents[page]
return <ComponentToRender />
}
Here's an example to play with :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With