Using React with Bootstrap Toggle

I want to use bootstrap toggle inside React . However, instead of a stylized element, a regular checkbox is displayed. How can this be fixed?

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap core CSS --> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"> <script src="https://fb.me/react-0.13.1.js"></script> <script src="https://fb.me/JSXTransformer-0.13.1.js"></script> <script type="text/jsx"> var WordCheckBox = React.createClass({ render: function() { return ( <div className="checkbox"> <label> <input type="checkbox" data-toggle="toggle" data-on="On" data-off="Off" /> option1 </label> </div> ); } }); React.render( <WordCheckBox />, document.getElementById('content') ); </script> <link href="https://gitcdn.imtqy.com/bootstrap-toggle/2.2.0/css/bootstrap-toggle.min.css" rel="stylesheet"> <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://gitcdn.imtqy.com/bootstrap-toggle/2.2.0/js/bootstrap-toggle.min.js"></script> </head> <body> <!--doesn't work. checkbox instead of toogle shown--> <div id="content"> </div> <!--works--> <div class="checkbox"> <label> <input type="checkbox" data-toggle="toggle" data-on="On" data-off="Off"> <span>option2</span> </label> </div> <!--works--> <div class="checkbox" data-reactid=".0"> <label data-reactid=".0.0"> <input type="checkbox" data-toggle="toggle" data-on="On" data-off="Off" data-reactid=".0.0.0"> <span data-reactid=".0.0.1">option3</span> </label> </div> </body> </html> 
+6
source share
3 answers

Based on your documents

You need to connect the plugin functionality when your React component is mounted (when it spits out HTML in the DOM)

Add a componentDidMount lifecycle binding and enter the ref attribute for this.

 var WordCheckBox = React.createClass({ componentDidMount: function() { $( this.refs.toggleInput.getDOMNode() ).bootstrapToggle(); } ... render: function() { ... <input ref="toggleInput" type="checkbox" data-toggle="toggle" data-on="On" data-off="Off" /> 
+6
source

If your input is added dynamically, as it was for me, you need to call the function in the componentDidUpdate function.

Also, you are likely to get class input instead of refs.

 componentDidUpdate() { $('.toggleInput').bootstrapToggle(); } 

And further:

 <input className="toggleInput" type="checkbox" checked data-toggle="toggle"> 
+2
source

on - Sets the switch to 'On'

off - Sets the switch to the off state

 componentDidMount: function() { $( this.refs.toggleInput.getDOMNode() ).bootstrapToggle('on'); } 
0
source

Source: https://habr.com/ru/post/985140/


All Articles