React JS: JSX
ReactJS JSX
1 Overview
📘 JSX JSX is a syntax extension for JavaScript that lets you write HTML-like markup inside a JavaScript file. Although there are other ways to write components, most React developers prefer the conciseness of JSX, and most codebases use it.
2 The problem
JSX: Putting markup into JavaScript
The Web has been built on HTML
, CSS
, and JavaScript
. For many years, web developers kept content in HTML
, design in CSS
, and logic in JavaScript
—often in separate files!
Content was marked up inside HTML while the page’s logic lived separately in JavaScript.
So, we need a way to put things together.
3 The solution: React JSX
todolist.jsx
4 React JSX is a optimal solution but
from David Ceddia
React cares exactly zero about styling. Think of it as generating the barebones HTML. React will put elements on the page, but everything after that is the job of CSS: how they appear, what they look like, how they’re positioned, and how centered or uncentered they are.
“How to center a div in React” is… not a React problem. It’s a CSS problem. You don’t need “react” in your Google query. Once you figure it out, use React to apply the right CSS class name to your components.
5 The Rules of JSX
To return multiple elements from a component, wrap them with a single parent tag.
JSX requires tags to be explicitly closed: self-closing tags like <img> must become <img />
, and wrapping tags like <li>oranges must be written as <li>oranges</li>
.
JSX turns into JavaScript and attributes written in JSX become keys of JavaScript objects. In your own components, you will often want to read those attributes into variables. But JavaScript has limitations on variable names. For example, their names can’t contain dashes or be reserved words like class.
6 The trick: JS in JSX with Curly Braces
JSX lets you write HTML-like markup inside a JavaScript file, keeping rendering logic and content in the same place. Sometimes you will want to add a little JavaScript logic or reference a dynamic property inside that markup. In this situation, you can use curly braces in your JSX to open a window to JavaScript.
That means it’s possible to use JavaScript inside it—with curly braces { }
.
todolist.jsx
todolist.jsx
todolist.jsx
const person = {
name: 'Gregorio Y. Zara',
theme: {
backgroundColor: 'black',
color: 'pink'
}
};
export default function TodoList() {
return (
<div style={person.theme}>
<h1>{person.name}'s Todos</h1>
<img
className="avatar"
src="https://i.imgur.com/7vQD0fPs.jpg"
alt="Gregorio Y. Zara"
/>
<ul>
<li>Improve the videophone</li>
<li>Prepare aeronautics lectures</li>
<li>Work on the alcohol-fuelled engine</li>
</ul>
</div>
);
}