1

I am developing a web app where I need to do certain things in React JS. I have written the react js code.

But I want it to be called only when a button is clicked. How to do this?

I read the tutorial but still couldn't figure out this.

Please help me. Struck for 2 hours.

sofs1
  • 3,834
  • 11
  • 51
  • 89

1 Answers1

2

If you wish to render a <ReactComponent/> at <div id="mountPoint"></div> using a button click and wish to pass an Object data to React, this should solve your problem.

The button below is not rendered using React. There must also be a mount point specified beforehand where React will mount the <ReactComponent/>:

<button onclick=ReactRender()> Render React </button>
<div id="mountPoint"></div>

The button calls a function ReactRender() which does all the rendering.

//Now to render React
var ReactRender = function(){
  // data is an Object which you wish to pass to React
  ReactDOM.render(<ReactComponent data={data}></ReactComponent>, mountPoint);
}

The data you have passed from outside React will be available as this.props.data inside ReactComponent.

Naisheel Verdhan
  • 4,905
  • 22
  • 34
  • Thanks for answering. If I am clicking a hyperlink, then is this correct? News – sofs1 Dec 17 '15 at 06:04
  • That should work. Just make sure you call the ReactDOM.render(...) function which does all rendering for you. For your above specific question, here's the answer http://stackoverflow.com/questions/10877485/better-way-to-call-javascript-function-in-a-tag – Naisheel Verdhan Dec 17 '15 at 06:08
  • Hi, Could you answer this please http://stackoverflow.com/questions/34328227/how-to-resolve-uncaught-typeerror-failed-to-construct-comment-please-use-th – sofs1 Dec 17 '15 at 06:44