Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate templates to external file in React

Tags:

reactjs

I am working on a ReactJS app for a client. I want the client to be able to customize some of the configurations and templates in the app. So I have created a config.js file

window.APP_CONFIG = {
    url: 'example.com',
    template: {
        item: '
            <div>
                <h3>A new item title</h3>
                { item.description }
            </div>
        '       
    }
};

How can I use this variable in my react app? I have tried the following but it gives me errors.

var app = React.createClass({

  render(){
     return (
       <div>
         {APP_CONFIG.template.item}
       </div>
     )
  }
})

Anyone has done something similar?

like image 633
vinay Avatar asked Dec 20 '15 12:12

vinay


Video Answer


1 Answers

You are not alone. React Templates allows you to use react without having to put up with inline jsx.

The react-templates syntax is very very similar to jsx but allows you to have your component html code in a separate .rt file - much cleaner. RT files have better support for looping and branching. Added bonus, you do not have to dance around reserved attribute names like "class" and "for" and there are other advantages.

From the docs:

Why not use JSX?

Some love JSX, some don't. We don't. More specifically, it seems to us that JSX is only a good fit for components with very little HTML inside. And this can be accomplished by creating DOM elements in code. Also, we like to separate code and HTML because it just feels right.

The main gotcha I've seen so far is that attribute values like onMouseDown={someJsExpr} are magically quoted in jsx but in react-templates you have to explicitly quote them a la onMouseDown="{someJsExpr}", no magic. I found that it was not hard to find cases of this and convert them over.

like image 135
Tom McClure Avatar answered Oct 18 '22 23:10

Tom McClure