Previous: , Up: ReactJS17   [Index]


1.2 Add JSX and ES2015+ Syntax to a Project Using Babel

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:

  1. Run npm init -y
  2. Run 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.

  1. Run JSX Preprocessor. Create a folder called 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.

  2. Now create a file called 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.
  3. As a bonus, this also lets you use modern JavaScript syntax features like classes without worrying about breaking older browsers. The tool we just used is called ‘Babel’, and you can learn more about it from its documentation.
'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: , Up: ReactJS17   [Index]