Is there any way to move the jsx from a component's render function to a separate file? If so, how do I reference the jsx in the render function?
Even though JSX had been around before React, it wouldn't have been nearly as popular without React picking it up. However, we can actually use JSX without React, and it's not that difficult either. The way React works is by configuring your bundler to convert JSX into calls to a createElement function.
Conclusion. JS is simply a scripting language, adding functionality into your website. JSX is an addition to the JavaScript syntax which is a mixture of both HTML and JavaScript. Both JS and JSX are interchangeable but JSX makes the code easier to understand for users.
React doesn't require babel but the library is built on the concept of using ES6 javascript syntax. React app however can be built with old ES5 syntax and JSX which would remove the need for Babel but you would lose the potential benefits of ES6.
You can use react-templates. It gives you exactly this separation between the markup and the component itself, and much more.
I found it very useful for my needs (a large scale web app).
One problem with moving templates into a separate file is that if you use handlers like:
var myTemplate = ( <form onSubmit={this.handleSubmit}></form> );
and then in your component you use:
render: function() { return myTemplate; }
the generated template code will call this.handleSubmit(), so the "this" will be wrong and the handlers won't work. What you need to do is put them in a function, like this:
var myTemplate = function() { return ( <form onSubmit={this.handleSubmit}></form> ); };
then in your component's render function, you need to bind it to 'this' correctly, then call it, like this:
render: function() { return myTemplate.bind(this)(); },
Now you can put that template definition anywhere, in a separate file or however you want to structure and reference your own code. (power to you! Don't listen to these crazy prescriptive frameworks! :) )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With