const hello = <h1>I love bunnies</h1>
When I first came across this line of code in React, I assumed it was HTML but I got to find out it is called JSX . Let us find out what this JSX can do in this article.
What is JSX
JXS which stands for JavaScript XML, in simple term is a special markup language that gives React components the feel of HTML with the power of JavaScript which is translated at runtime. Using JSX you can write HTML like structure in the same file as JavaScript then Babel will transform these expressions into actual JavaScript code.
import React from 'react';
import './App.css';
function App() {
return <h1>Hello, World</h1>;
}
export default App;
This looks a lot like basic HTML, but it is not, this is a typical example of how JSX is expressed in react. If you check this in your browser, you should get this:
Nesting in JSX
When writing JSX, you are expected to wrap the expression in parentheses. Since the JSX spans multiple lines. Just like this:
import React from 'react';
import './App.css';
function App() {
return(
<h1>Hello, World</h1>
<p>I Love React </p>
)
}
export default App;
Top-level element
This example will most likely throw an error, so if you want to return another element in this function, you must return a single element. The element can have nested children, but there must be a single top-level element. In order to fix the errors in the example, all we have to do is wrap both elements in a Tag. This returns the function as a single element. Just like this:
import React from 'react';
import './App.css';
function App() {
return(
<div>
<h1>Hello, World</h1>
<p>I am writing JSX</p>
</div>
)
}
export default App;
You can think of JSX as a shorthand for calling React.createElement().
Expressions in JSX
When writing expressions, either React variables or property or any valid JavaScript expression, you are expected to wrap them in curly braces {} . Just like this:
const element = <h1>React is {10 + 10} times better with JSX</h1>;
Styling in JXS
When writing HTML, we use class name attributes, but in JSX we use className because class is not recognized and Since JSX is closer to JavaScript than HTML, JSX properties make use of camelCase ( handleClick) naming convention instead of HTML attribute names.
The Keys
When making a list in JSX, your list should include a JSX attribute called Keys. Keys are similar to id and they are used internally by React to keep track of the list items. React might scramble the order of the list if you do not use the keys.
const mustDo = (
<ul>
<li key = "todo-1"> write</li>
<li key = "todo-2"> code </li>
<li key = "todo-3"> find a bug </li>
</ul>
);
NOTE:
- Elements must be close properly else an error gets thrown.
- Parentheses are used to wrap multiple lines.
- Wrap all child elements in a single parent element .