Ad
Switching My Inner Div To The Other Side In A Switch Button
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
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad