Reputation: 151
I am controlling what component should be shown on my applications screen via the state and a switch statement in the main render function. I am writing this in react-native but this is a react structure question.
I also have a Navbar component that I would ideally like to only rerender when the user clicks on a link in the Navbar itself, but I don't know of a great way to do this with how I have the switch statement setup now, it seems like I will have to rerender the Navbar every time depending on what condition is met by the state.
My question is, is there a way that I can still use conditional rendering of components in the render method like I am below AND have a component that is always rendered at the top of the screen like the Navbar? I know this is possible with things like React Router, but is there a better way to structure it without using a tool like React Router or having to rerender the NavBar component every time?
import React from 'react';
import GPS from './GPS/gps';
import Home from './Home';
import Photo from './Camera/Photo';
export default class App extends React.Component {
constructor() {
super();
this.state = {
hasCameraPermission: null,
type: Camera.Constants.Type.back,
currentView: null,
currentImage: null,
navigation: 'Overview'
};
this.updateNavigation = this.updateNavigation.bind(this);
}
updateNavigation(view) { //Update view function
this.setState({currentView: view});
}
render() {
const { currentView } = this.state;
switch(currentView) {
case null:
return (
<Home updateNav={this.updateNavigation} />
);
break;
case 'GPS':
return (
<View>
<GPS />
<Text onPress={() => this.setState({currentView: null})}>Back</Text>
</View>
);
break;
case 'Camera':
return (
<Photo updateNav={this.updateNavigation} />
);
break;
case 'viewPicture':
return (
<View>
<Image source={{uri: this.state.currentImage.uri}} style={{width: this.state.currentImage.width/10, height: this.state.currentImage.height/12}} />
</View>
);
break;
}
}
}
Upvotes: 5
Views: 5498
Reputation: 34014
Always keep render as much as clean.
You can use && operator to do the same instead of using switch case. Use && operator and check every case and render accordingly. Check below code for better understanding.
render() {
const { currentView } = this.state;
return(
{currentView == null && (
<Home updateNav={this.updateNavigation} />
)}
{currentView == "GPS" && (
<View>
<GPS />
<Text onPress={() => this.setState({currentView: null})}>Back</Text>
</View>
)}
{currentView == "Camera" && (
<View>
<Photo updateNav={this.updateNavigation} />
</View>
)}
{currentView == "viewPicture" && (
<View>
<Image source={{uri: this.state.currentImage.uri}} style={{width: this.state.currentImage.width/10, height: this.state.currentImage.height/12}} />
</View>
)}
)
}
Upvotes: 3