'Render between start and stop button in React Native
I wanna render between displaying a start and stop button based on pressing the buttons. That means if the start button gets pressed the stop button should be showed and vice versa. In the standard case the stop button should be rendered. With the following code I get an error because status
can be read only so I need some other way to set the status.
const SampleComponent = () => {
const startButton = () => {
return <Component1 />;
};
const stopButton = () => {
return <Component2 />;
};
const status = stopButton;
return (
<View>
<Pressable
onPress={() => {
if (status == stopButton) {
status = startButton;
} else {
status = stopButton;
}
}}
>
{status}
</Pressable>
</View>
);
};
export default SampleComponent;
I need a React Native way to do this. I tried to study the docs and also other material but I just don't get it.
Solution 1:[1]
React way of doing this would be to use state hook. You could use a boolean state variable and toggle it on button click.
Solution 2:[2]
Solution
const SampleComponent = () => {
const StartButton = () => {
return <Component1 />;
};
const StopButton = () => {
return <Component2 />;
};
const [status, setStatus] = useState(false);
return (
<View>
<Pressable
onPress={() => {
setStatus(!status);
}}
>
{status ? <StopButton /> : <StartButton />}
</Pressable>
</View>
);
};
export default SampleComponent;
Remember to give components uppercase letter.
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 | sushrut619 |
Solution 2 | Max Hager |