cham
cham

Reputation: 10702

How does importing React allow JSX to be processed as JS?

I'm learning React with create-react-app and I understand how to make components with JSX. For example a simple stateless component is something like:

import React from 'react';

const Widget = (props) => <h1>{props.text}</h1>

export default Widget;

So importing React uses createElement() for the conversion of the HTML-looking JSX (<h1>{props.text}</h1>), but how is that function applied? It's not like I am explicitly using React for anything. If there is some kind of compiling go on as the app is built, then why does React need to be imported?

Upvotes: 1

Views: 153

Answers (2)

cs01
cs01

Reputation: 5763

Importing React doesn't convert JSX into HTML; Babel does that. Babel is a JavaScript compiler.

Babel effectively turns

// Display a "Like" <button>
return (
  <button onClick={() => this.setState({ liked: true })}>
    Like
  </button>
);

into

// Display a "Like" <button>
return React.createElement(
  'button',
  { onClick: () => this.setState({ liked: true }) },
  'Like'
);

Read more in the React docs Add JSX to a Project.

Upvotes: 1

devserkan
devserkan

Reputation: 17608

First, Babel compiles JSX into regular Javascript, then your React import, more accurately React.createElement function does the job. Here is the compiled version of your code:

"use strict";

var Widget = function Widget(props) {
  return React.createElement(
    "h1",
    null,
    props.text
  );
};

Upvotes: 1

Related Questions