Previous: Adding React to a Web Page, Up: ReactJS17 [Index]
Adding JSX to a project doesn’t require complicated tools like a bundler or a development server. Essentially, adding JSX is a lot like adding a CSS preprocessor. The only requirement is to have Node.js installed on your computer.
Go to your project folder in the terminal, and paste these two commands:
npm init -y
npm install babel-cli@6 babel-preset-react-app@3
Both React and the application code can stay as ‘<script>’ tags with no changes. You just added a production-ready JSX setup to your project.
src
and run this terminal
command, which starts an automated watcher for JSX.
npx babel --watch src --out-dir . --presets react-app/prod
npx
is a package runner tool that comes with npm 5.2+
.
See this article describing npx.
src/like_button.js
with this JSX starter code,
the watcher will create a preprocessed like_button.js
file containing
plain JavaScript code suitable for the browser. When you edit the source
file with JSX, the transform will re-run automatically.
'use strict'; class LikeButton extends React.Component { constructor(props) { super(props); this.state = { liked: false }; } render() { if (this.state.liked) { return 'You liked this.'; } return ( <button onClick={() => this.setState({ liked: true }) }> Like </button> ); } } let domContainer = document.querySelector('#like_button_container'); ReactDOM.render(<LikeButton />, domContainer);
Previous: Adding React to a Web Page, Up: ReactJS17 [Index]