React is a popular JavaScript library for building user interfaces. And in order create complex and efficient web applications, you’ll need to understand its fundamental concepts.
What is JSX ?
JSX stands for JavaScript XML. Its an extension of the JavaScript language based on ES6. Its translated into regular JavaScript at runtime.
JSX allows us to write HTML in React which makes the process of writing HTML in your React apps much easier.
Why use JSX ?
JSX is not mandatory, it is totally up to you whether to use plain HTML or JSX. below code is example for plain HTML and JSX
//Plain HTML
const myElement = React.createElement('h1', {style:{color:"green"}}, 'Not to use JSX')
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(myElement);
// JSX
const myElement = <h1>JSX!</h1>;
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(myElement);
As you can see in the first example, using plain HTML makes it a bit more difficult to create elements. We need to use a createElement method, then pass the element along with its style and its value.
On the other hand, JSX makes it much easier by simply using the element tag just as we write HTML and passing its value.
JSX Rules
- A React component name must be capitalized. Component names that do not begin with a capital letter are treated like built-in components.
- JSX allows you to return only one element from a given component. This is known as a parent element
If you want to return multiple HTML elements, simply wrap all of then in a single <div></div>, <React.fragments><<React.fragments/>, <></> or any semnatic tag.
const App = () => {
return
<div>
<h1>Hello World!</h1>
</div>
}
But this won’t work, because return would be interpreted as a plain return statement. To avoid that, you need to encapsulate everything inside ( ).
const App = () => {
return (
<div>
<h1>Hello World!</h1>
</div>
);
}
- In JSX, every tag, including self closing tags, must be closed. In case of self closing tags you have to add a slash at the end
const App = () => {
return (
<>
<img src="./assets/react.svg" alt="" />
</>
);
}
- Since JSX is closer to JavaScript than to HTML, the React DOM uses the camelCase naming convention for HTML attribute names.
- “class” and “for” are reserved keywords in JavaScript, so use “className” and “forHTML” instead, respectively.