Let's address the elephant in the room first. You will be writing XML with your React code.
JSX is a preprocessor step that adds XML syntax to JavaScript. You can definitely use React without JSX but JSX makes React a lot more elegant.
Just like XML, JSX tags have a tag name, attributes, and children. If an attribute value is enclosed in quotes, the value is a string. Otherwise, wrap the value in braces and the value is the enclosed JavaScript expression.
<div className="red">Children Text</div>;
<MyCounter count={3 + 5} />;
// Here, we set the "scores" attribute below to a JavaScript object.
var gameScores = {
player1: 2,
player2: 5
};
<DashboardUnit data-index="2">
<h1>Scores</h1>
<Scoreboard className="results" scores={gameScores} />
</DashboardUnit>;
The above gets compiled to the following without JSX. I hope you will agree JSX syntax reads more naturally.
React.createElement("div", { className: "red" }, "Children Text");
React.createElement(MyCounter, { count: 3 + 5 });
React.createElement(
DashboardUnit,
{ "data-index": "2" },
React.createElement("h1", null, "Scores"),
React.createElement(Scoreboard, { className: "results", scores: gameScores })
);
You'll notice that React uses className
instead of the traditional DOM class
. From the docs, "Since JSX is JavaScript, identifiers such as class
and for
are discouraged as XML attribute names. Instead, React DOM components expect DOM property names like className
and htmlFor
, respectively."
If want to learn more about JSX, check out the official JSX documentation. You can also try the live Babel REPL.
Try to match the markup of the box contents. I recommend referring to the HTML tab and/or inspecting the DOM.
Components are the building blocks of React. Master them and see a new side of web development.
Subscribe for a range of articles from React basics to advanced topics such as performance optimization and deep dives in the React source code.