Home > Net >  Render between start and stop button in React Native
Render between start and stop button in React Native

Time:05-14

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.

CodePudding user response:

React way of doing this would be to use state hook. You could use a boolean state variable and toggle it on button click.

CodePudding user response:

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.

  • Related