Ternary State Toggle in BootStrap-React

I’m confused by the syntax of using a ternary toggle to change the state to the opposite of whichever it currently is.
I got a button to change from Start to Stop, but only on the first click
now I’m trying to get it to change back.
I’d also like it to change the className from “success” to “danger”. Or the background color from Green to Red and back.
But it looks like I’m too late in the rendering, React-BootStrap has already compiled to class btn-sucess before the rerendering.

repo
live demo

Toggle.js

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Button, Container, Row, Col } from 'react-bootstrap';

export class Toggle extends Component {
  constructor(props) {
    super(props);
    // Initial State
    this.state = {
      tglStart: "Start",
      tglVariant: '"success"',
    };

    // This binding is necessary to make `this` work in the callback
    this.setQuote = this.setQuote.bind(this);

  }

  static propTypes = {
    tglStart: PropTypes.string.isRequired,
    tglVariant: PropTypes.string.isRequired,
  };

  setQuote(tglStart) {
    this.setState({
      tglStart: "Stop",
      tglVariant: `"danger"`,
    });
  }

  render() {
    let { tglStart } = this.state;
    let { tglVariant } = this.state;
    return (
      <Container>
        <Row className="justify-content-center">
          <Col as={Button} variant="success" xs={2} sm={2} md={2} lg={2}
            onClick={this.setQuote}>
            <h1>
              {tglStart}
              <br></br>
              {tglVariant}
            </h1>
          </Col>
        </Row>
        {/* <Row className="justify-content-center">
          <Col as={Button} variant="success" xs={2} sm={2} md={2} lg={2} >
            <h1>
              Stop
            </h1>
          </Col>
        </Row>
        <Row className="justify-content-center">
          <Col as={Button} variant="danger" xs={2} sm={2} md={2} lg={2} >
            <h1>
              {tglVariant}
            </h1>
          </Col>
        </Row> */}
      </Container>
    );
  }
}

export default Toggle;

Screenshot from 2020-12-29 23-23-45

And… where in this code have you tried to set it back to start?

ok, this is what I came up with and it seems to work

  setToggleOnOff() {
    let { tglStart } = this.state;
    (tglStart === "Start") ?
      this.setState({
        tglStart: "Stop",
        tglVariant: 'btn-danger',
      }) :
      this.setState({
        tglStart: "Start",
        tglVariant: 'btn-success',
      });
  }

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.