JSX
JSX
JSX is a syntax extension for JavaScript that lets you write HTML-like markup inside a JavaScript file.
In React, rendering logic and markup live together in the same place — components.
Rules of JSX
1.Return a single root element
Multiple elements must be wrapped inside a single parent tag or inside an empty tag. (Parent only 1) WHY? [Under the hood JSX is transformed into plain JavaScript objects, you cannot return two objects from a function without wrapping them into an array]
This empty tag is called a Fragment. Fragments let you group things without leaving any trace in the browser HTML tree.
2. Close all the Tags
<h1> ……. </h1>
<img src=’…’ /> Event Self Closing Ones like img <img />
<a href=’…’ />
3.camelCase most of the things
many HTML and SVG attributed are written in camelCase e.g stroke-width
1. becomes strokeWidth.
Since class is a reserved keyword, you have to write className
aria-* and data-* attributes are written with dash (not camelCase)
JSX with Curly Braces
You can use curly braces in your JSX to open a window to JavaScript.
- As attributes
Immediately following the = sign:
src={avatar} will read the avatar variable,
but src=”{avatar}” will pass the string “{avatar}”
className -> cartoon //String
alt -> Mickey Mouse //JavaScript Variable in curly braces
2.As text directly inside a JSX tag:
3. Any JavaScript expression will work between curly braces, including function calls like formatDate():
const today = new Date();
<h1>To Do List for {formatDate(today)} </h1>
4.Using “double curlies”: CSS and other objects in JSX
Objects themselves are also denoted with curly braces so to pass them in JSX, add another curly brace
Object: {name: “Alex” , age: 15}
JSX: {{name: “Alex” , age: 15}}
Example: Inline CSS style pass as style object
style attribute needs an object so we are passing person.theme which is an object having properties (CSS properties) and values (CSS Values)
[theme object inside person object]
And person.name is just an object property (variable) so nest inside {}
You cannot do this
<h1> I am {person} </h1> //Render whole object as text
5. Another Example Concatenating strings