Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js: how to decouple jsx out of JavaScript

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?

like image 862
tldr Avatar asked Jan 11 '14 19:01

tldr


People also ask

Can you use JSX outside of React?

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.

Can I use JS instead of JSX?

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.

Can JSX be used without babel?

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.


2 Answers

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).

like image 52
tomericco Avatar answered Sep 22 '22 00:09

tomericco


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! :) )

like image 45
Damon Smith Avatar answered Sep 22 '22 00:09

Damon Smith