Reputation: 33
I'm trying to work with React. I got a HTML page with some contents and a corresponding JS script holding the logic. Now I decided to use React to dynamically create some reusable view components within a button click event.
Simple example:
HTML
<script src="/ReactTester/react/react.js"></script>
<script src="/ReactTester/react/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
<script src="/ReactTester/myreact.js" type="text/babel"></script>
<button onclick="button_click()">Button</button>
<div id="example"></div>
React + JS
var HelloWorld = React.createClass(
{
render: function()
{
return(<h1>Hello, world!</h1>);
}
});
var button_click = function ()
{
ReactDOM.render(<HelloWorld/>, document.getElementById('example'));
}
When I click the button I get the error
ReferenceError: 'button_click' is not defined
If I try to render the element without using the button event everything works fine. It seems to be a problem with mixing React and normal JS code. Am I missing something? What's wrong?
Any hint would be great. Thanks in advance!
Upvotes: 3
Views: 3347
Reputation: 6803
Try this
var HelloWorld = React.createClass({
render: function() {
return (
<h1>Hello, world!</h1>
);
}
});
var button_click = function () {
ReactDOM.render(<HelloWorld />, document.getElementById('example'));
}
document.getElementByTagName('button')[0].addEventListener('click', button_click);
Upvotes: 3
Reputation: 8686
The button_click
function defined in your file is not available in the global scope. If you attach to the global scope via the window
object for example : window.button_click = ...
that will work. But explicitly attaching the event handler as stated in the other answer is a better option since there is no global scope pollution.
Upvotes: 0