0

I am calling react component from html using jQuery like below code

$(document).ready(function(){
  const display = $("#check").prop("checked");
  if(display){
     $("#myWidget").attr("display", display);
  }
});
<div class="form-group">
        <div class="checkbox">
          <label><input type="checkbox" value="test" id="check"</label>
        </div>
      </div>
      
      <react-comp display="display"  id="myWidget" style="flex:1"/>

Is it the right way to call react component? Do we have another way apart from jquery and pure document object?

Vikas Yadav
  • 3,094
  • 2
  • 20
  • 21

3 Answers3

0

You don't need JQuery if you are using React, except if you need it for something else I suggest removing JQuery fully,because React can provide and fully replace all of JQuery functionalities, with appropriate external libraries of course.

As for Rendering maybe use the ReactDOM.render(), something like this:

ReactDOM.render(
  element, //element is a reference to your React Component here
  document.getElementById('myWidget')
);

https://reactjs.org/docs/rendering-elements.html

I am not sure what you are trying to achieve, but if it is just showing/rendering the react component, ReactDOM.render() is the way to go.

If you want it inside the html, either use an external .js file(usually you bundle your React code and then reference the external bundle.js inside a script tag). Or if you don't want that, just import ReactDOM straightforward and use it inside a script tag again.

0

Facebook has a nice page for this outlining how to properly reference elements. Basically it boils down to giving an element a reference callback like so:

<react-comp display="display" style="flex:1" ref={(ref) => this.myWidget = ref} />

Then you can access it like so:

this.myWidget.attr("display", "whatever you want to set it to");
Remy Kabel
  • 946
  • 1
  • 7
  • 15
0

  componentDidMount(props){
  const display = this.myCheckBox.prop("checked");
  if(display){
     //DOM base way:
     //this.myWidget.attr("display", display);
     //or variable base (better choice):
     this.widgetDisplay = display;
  }
  }
<div className="form-group">
        <div className="checkbox">
          <label><input type="checkbox" ref={(element)=>this.myCheckBox=element} value="test" id="check"></label>
        </div>
      </div>
      <react-comp ref={(element)=>this.widgetDisplay=element} display={this.widgetDisplay}  id="myWidget" style="flex:1"/>
javad bat
  • 4,236
  • 6
  • 26
  • 44