JSX expressions are expressions used inside a JavaScript file that can be rendered as an HTML DOM element.
const hello = <h1>Hello world</h1>;
In the above example, a variable named 'hello' is declared and is assigned the JSX expression <h1>Hello world</h1>
JSX enables us to use expressions almost identical to that of HTML elements inside JavaScript, and we can render these to be shown on the browser by using React.
JSX cannot be used in any JavaScript file.
It can only be used with the React library.
import React from 'react'; import ReactDOM from 'react-dom';
Above codes import the React
and ReactDOM
objects from the react
and react-dom
libraries, respectively.
Importing the React
and ReactDOM
objects make it possible for us to use their properties and methods inside our JavaScript file.
The React library has many properties and methods, one of which is .createElement()
method.
When a JSX expression is used in React, what happens is that the expression is actually calling the React.createElement()
method.
const hello = <h1>Hello world</h1>;
above code is the same as:
const hello = React.createElement( 'h1', null, 'Hello world' );
Another example:
const dogPic = <img className='dog-img' alt='dog' src='/img/dog.png' />;
is same as:
const dogPic = React.createElement( 'img', {className: 'dog-img', alt: 'dog', src: '/img/dog.png'} );
Following is NOT allowed:
const hello = <h1>Hello world</h1> <p>Hello~</p>;
To fix the issue of having more than one element in a single JSX expression, add an outermost element to wrap around the elements:
Following is OK:const hello = ( <div> <h1>Hello world</h1> <p>Hello~</p> </div> );
()
:Following doesn't work:
const hello = <div> <h1>Hello world</h1> <p>Hello~</p> </div>;
Following works:
const hello = ( <div> <h1>Hello world</h1> <p>Hello~</p> </div> );
class
attribute, you must use className
insteadclass
in JavaScript is a reserved nameHTML:
<h1 class='hello'>Hello world</h1>
JSX:
<h1 className='hello'>Hello world</h1>
{}
const helloString = 'Hello world'; const hello = <h1>{helloString}</h1>;
const add = <p>10 + 10</p>; // Result: 10 + 10
const add = <p>{10 + 10}</p>; // Result: 20
if
statements inside JSX expressionsif
statements outside the JSX expressions&&
operator
who need help improving their coding skills butterfly locs, daily game solve cross