react fundamentals -jsx


What is jsx ?
JSX stands for JavaScript XML. It's an extension of the JavaScript language based on ES6. It's 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. But the code blocks I'll share below will clarify the differnece between plain HTML and JSX and which one is preferable.
//plain html
const myElement = React.createElement('h1', { style:{color:"green"} }, 'I do not use JSX!');
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(myElement);
// JSX
const myElement = <h1>I Love JSX!</h1>;
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(myElement);
as we see in above plain html it a bit complex to create elements , as we need use the method to create element and then pass the element along with style.
on the other hand in jsx we need use the element tag and write the html
Rules in jsx
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 them in a single <div></div>
, <React.fragments><React.fragments/>
, <></>
or any semnatic tag.
const App = () => {
return
<div>
<h1>Hello World!</h1>
<p>Tanishka here!</p>
</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(
<>
<h1/>
<h2/>
<>
)
}
How to use CSS in JSX
While working with JavaScript we typically have a HTML file, a CSS file, and a JavaScript file, right? Simple. But while working with React, we use HTML (JSX) and JavaScript in the same file.
To add style to our components, we can either use inline CSS or external CSS.
Let's first see how inline CSS works in React.
JSX represents objects, that is key-value pairs – like a property name and its value. Always write the value in " "
as we do in objects.
So when we're adding inline styles to JSX elements, we must add { } for object representation (outer { } is the convention).
const App = () => {
return (
<>
<h1 style={ { color: "Red" } }>Hello World!</h1>
<p style={ { fontSize: "20px" } }>Tanishka here!</p>
</>
);
}
that it for today a very clean start and undersatanding the founation of react
HAPPY CODE WITH REACT….SMD
Subscribe to my newsletter
Read articles from SMD OWAIS directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

SMD OWAIS
SMD OWAIS
just learning the tech and speak it out