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) {
    this.state = {
      checked: false
    this.onChange = this.onChange.bind();

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

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



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 className={!this.state.checked ? "switch-rectangle-box" : ""}>

Also, adding to the above a recommendation would be to use Material UI switches and not reinvent the wheel.