mshameer mshameer - 1 year ago 69
React JSX Question

How to Separate Jsx inside render function into a separate file in ES6? or any other solution in react to separate the Logic and presentation?

Here is the code in ES5 in which the jsx is written into a separate file

import React from 'react';
import Template from './template.jsx';

const DetailElement = React.createClass({
render: Template

export default DetailElement;
enter code here

template.jsx file will be like this

import React from 'react';

const render = function() {

return (
<div>Hello World</div>

export default render;

How can I write the same using ES6 Classes ? Or any other solution is available to do this separation ?

I have got the ES6 code something like this

import React, {Component} from 'react';
import Template from './template.jsx';

export default DetailElement extends Component {
componentDidMount() {
// some code
DetailElement.prototype.render = Template;

Yes this is working.

Answer Source

Yes you can do it your template code is like a functional comoponent basically it is a function that returns jsx. You just need to render your template in your DetailElement class

import React from 'react';
import Template from './template.jsx';

class DetailElement extends React.Component{
  render = Template

export default DetailElement;

here is an example I created codepen link now is a es6 class feature that you can define class property outside class or babel transformer that you need to check

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download