Ad

Switching My Inner Div To The Other Side In A Switch Button

- 1 answer

I am working on a switch/toggle button component in React I have managed to create two div's with on inside of the other using Js and css. My question is how can I toggle it so that it will move from one side to the other and also make the background of the parent div change once the child div is moved/switched/toggle to the other side of the parent div.

Thanks in advance.

class Switch extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      checked: false
    }
    this.onChange = this.onChange.bind();
  }

  onChange = () => {
    this.setState({ 
      checked: !this.state.checked});
      console.log(this.state.checked)
    } 

render () {
  return (
  <div className='switch-box' checked={this.state.checked} onClick={this.onChange} >
    <div className='switch-rectangle-box'>
    </div>
    <div className='switch-inside-box'></div>
  </div>
  );
}

}

 export default Switch
.switch-rectangle-box {
  color: $grey;
  display: inline-block;
  min-width: 44px;
  height: 22px;
  background-color: $grey;
  border: 1px solid transparent;
  border-radius: 100px;
  cursor: pointer;
}

.switch-inside-box {
  position: absolute;
  top: 1px;
  left: 1px;
  width: 18px;
  height: 18px;
  background-color: $light;
  border-radius: 18px;
  cursor: pointer;
}

Ad

Answer

The question has a lot of ifs/else.

But from what seems to be the problem, I'm guessing you need something like the following

<div className={this.state.checked ? "switch-rectangle-box" : ""}>
</div>
<div className={!this.state.checked ? "switch-rectangle-box" : ""}>
</div>

Also, adding to the above a recommendation would be to use Material UI switches and not reinvent the wheel. https://material-ui.com/components/switches/

Ad
source: stackoverflow.com
Ad