'React Native - How to switch between views efficiently?
I have a couple of Views that render an entire page and I want to switch between them. I could use a screen for each view and navigate between screens but that would be a bit bad UX to show a transition everytime. See it like some tabs at the top of the page that each render different content.
I've been doing it with conditionals like below. Is there another way to do this more efficiently?
import React, { useState, useEffect } from 'react';
import {StyleSheet, View, Image, Text, Dimensions, ImageBackground, Button} from 'react-native';
const RM = ( {route, navigation } : any) => {
const [view, setView] = useState("A");
return (
<>
<View>
<Button onPress={() => setView("A")} title="Set A" />
<Button onPress={() => setView("B")} title="Set B" />
<Button onPress={() => setView("C")} title="Set C" />
</View>
<View>
{view === "A" && (
<ComponentA />
)}
{view === "B" && (
<ComponentB />
)}
{view === "C" && (
<ComponentC />
)}
</View>
</>
);
};
export default RM;
Solution 1:[1]
Multiple conditions and rendering different views can be handled nicely with switch case
I have used class component here but same can be achieved in functional components.
class RM extends React.Component {
constructor(props){
super(props)
this.state = {
selectedTab: ''
}
}
setTab = (tab) => {
this.setState({selectedTab: tab})
}
selectedTab = () => {
switch(this.state.selectedTab){
case 'A':
return <ComponentA />
case 'B':
return <ComponentB />
case 'C':
return <ComponentC />
default:
return /* empty div maybe */
}
}
render() {
return(
<View>
<View>
<Button onClick={() => setTab('A')} />
<Button onClick={() => setTab('B')} />
<Button onClick={() => setTab('C')} />
</View>
{this.selectedTab()}
</View>
)
}
}
For the functional component you can do something like this:
const RM = () => {
const [selectedTab, setSelectedTab] = useState('');
const SelectedTab = () => {
switch(selectedTab){
case 'A':
return <ComponentA />
case 'B':
return <ComponentB />
case 'C':
return <ComponentC />
default:
return /* empty div maybe */
}
}
return(
<View>
<View>
<Button onPress={() => setSelectedTab('A')} />
<Button onPress={() => setSelectedTab('B')} />
<Button onPress={() => setSelectedTab('C')} />
</View>
{SelectedTab()}
</View>
)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Nick Bartlett |