React JSX
Explore the basics of React JSX to understand how to combine HTML and JavaScript in components. Learn the essential syntax rules like returning a single root element, closing tags, and using camelCase attributes. This lesson helps you confidently render strings, objects, and expressions in JSX to build user interfaces in React.
We'll cover the following...
In React, the returned output of the App component resembles HTML. This output is called JSX, which mixes HTML and JavaScript to create a powerful react syntax for building user interfaces. Let’s see how this works for displaying a variable:
.App {
text-align: center;
}
.App-logo {
animation: App-logo-spin infinite 20s linear;
height: 80px;
}
.App-header {
background-color: #222;
height: 150px;
padding: 20px;
color: white;
}
.App-title {
font-size: 1.5em;
}
.App-intro {
font-size: large;
}
@keyframes App-logo-spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
📜Note: In the app onwards we can now see the output in the browser since we are starting the app using
npm start. This will start the live-server, which will then begin to listen for any changes made in our code files.
See the output in action, both in the output tab and the host link provided below. In case of any changes you make to your code, the live-server will detect these, just press Run.
📜Note: The terminal remains alive for 30 minutes for each session, after which the server is killed;
The application is started with npm start, and now you can look for the rendered variable in the browser, which should read: “Hello React”.
The Rules of JSX
While JSX looks like HTML, it is actually closer to JavaScript. Because of this, there are specific Rules of JSX you must follow to ensure your code compiles correctly:
- Return a single root element: A component must return a single parent element (like a
<div>or a Fragment<>). - Close all tags: All tags must be explicitly closed, including self-closing tags like
<img />or<input />. - Use camelCase for attributes: Since JSX turns into JavaScript, attributes like
stroke-widthbecomestrokeWidth. - Attribute replacements: Some keywords are reserved in JavaScript (like
classorfor), so JSX uses alternatives.
Let’s focus on the HTML, which is expressed almost the same in JSX. An input field with a label can be defined as follows: