|
There are a few ways you could build a working site from undo76’s example. Unfortunately all the noise around modern JS does make it seem more complicated than it really is, but you can set up everything you need in about two minutes. The only essentials you need are React itself and, because the example uses ES2015 and JSX code, Babel to transpile the script into more portable JS that will run in today’s browsers. In practice you’d probably also be using Node/NPM to manage packages and a tool like Browserify or Webpack to resolve dependencies. I’ll use Browserify. So, here is a complete working example. For the script, we’ll use undo76’s original code verbatim, and add imports of the React modules at the start of the file. Let’s call this index.src.js: import React from "react";
import ReactDOM from "react-dom";
const DATA = {
name: 'John Smith',
imgURL: 'http://lorempixel.com/100/100/',
hobbyList: ['coding', 'writing', 'skiing']
}
const App = ({ profileData }) => (
<div>
<Profile { ...profileData } />
<Hobbies { ...profileData } />
</div>
);
const Profile = ({ name, imgURL }) => (
<div>
<h3>{name}</h3>
<img src={imgURL} />
</div>
);
const Hobbies = ({ hobbyList }) => (
<div>
<h5>My hobbies:</h5>
<ul>
{ hobbyList.map( (hobby, idx) => (
<li key={ idx }>{ hobby }</li>
))}
</ul>
</div>
);
ReactDOM.render(<App profileData={DATA} />, document.getElementById('content'));
As usual, we need an HTML file to load that script, though it doesn’t need to do much else except provide a <div> with an ID where we’ll put the content that React renders. Otherwise just use your preferred boilerplate. Let’s call this index.html: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>React test</title>
</head>
<body>
<div id="content"></div>
<script src="index.js" charset="utf-8"></script>
</body>
</html>
Finally, we need the tools and React packages: npm init
npm install --save react react-dom
npm install --save-dev browserify babelify babel-preset-es2015 babel-preset-react
Now we can run Browserify to generate our output JS file (adjust the / to \ if you’re running on Windows): node_modules/.bin/browserify index.src.js -o index.js -t [ babelify --presets [ es2015 react ] ]
That will produce index.js, which is just the code from undo76 linked with React and then transpiled to a more portable level of JS that today’s browsers can cope with. (Incidentally, this is literally the first example on the Babelify documentation page, which gives you an idea of how routine it is once you’re familiar with these tools.)Now load index.html in your browser of choice and enjoy. :-) |