DEV Community

loading...
Cover image for Core React Concept: JSX

Core React Concept: JSX

Ayu Adiati
🇮🇩 based in 🇳🇱 || Stay home mom 👨‍👩‍👧 || Love 📸 & 🍣 & ☕ || Self-taught 👩‍💻 || Full-stack developer in the making ⚒
・3 min read

Hello Fellow Codenewbies 👋,

Let's say that we want to create an element in DOM that has not existed yet and append it to a div with ID "root".
Then this is what we would do in vanilla Javascript:

HTML:

<body>
  <div id="root"></div>
</body>
Enter fullscreen mode Exit fullscreen mode

Javascript:

const root = document.getElementById('root')
const h1 = document.createElement("h1")

h1.innerHTML = "Hello World"
root.appendChild(h1)
Enter fullscreen mode Exit fullscreen mode

React has a unique syntax called JSX which will benefit us from writing long codes as above.


What Is JSX?

JSX is a syntax extension to JavaScript.
It allows us to combine UI with Javascript logic in a Javascript file.

ReactDOM.render(<h1>Hello World</h1>, document.getElementById("root"))
Enter fullscreen mode Exit fullscreen mode

In the example above, we have a <h1> tag inside Javascript's method.
It is saying, "Render <h1> in an element with ID root".

Notes:
Please read the previous post, if you haven't, to understand how ReactDOM.render() works.

Since JSX is a combination of HTML and Javascript, we need Babel to translate JSX and render the HTML onto the page.

  • When we use CDN, we need to include Babel's CDN.

    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    
    
  • We need to import the React library to enable Babel when we use the create-react-app package.

    import React from 'react'
    

Notes:
It's optional, but we can save files that contain JSX codes as .jsx instead of .js (e.g.: Header.jsx). That way, we are aware that the files have JSX codes in them.

Many Elements In JSX

It's important to note that we cannot have more than one element next to each other in JSX.
When we have many elements to render, we need to wrap those elements inside an opening and closing tag.
Some developers use fragments (<></>), and some use <div></div> as a wrapper.
For accessibility purposes, we better use fragments because they won't give extra <div>. Thus, it's less confusing for people who use screen readers.

const element = (
  <>
    <h1>Hello World</h1>
    <p>How are you?</p>
  </>
)

ReactDOM.render(element, document.getElementById("root"))
Enter fullscreen mode Exit fullscreen mode

For a good readable purpose, it's common practice to wrap a return JSX code in ().

Anything that lives inside the opening and closing wrapper tag is called children property.

Closing Tag

JSX is more strict than HTML.
One basic rule of JSX is that every element has to have a closing tag.
Think about HTML tags such as <input>, <img>, <br>, <hr>, and so on.
In JSX, we have to close those tags, otherwise, we will get syntax errors.

const element = (
  <>
    <h1>Hello World</h1>
    <br />
    <p>How are you?</p>
    <input type="text" placeholder="Type your message" />
    <button>Submit</button>
  </>
)

ReactDOM.render(element, document.getElementById("root"))
Enter fullscreen mode Exit fullscreen mode

Embedding Javascript In JSX

In the previous example, we hardcoded the heading and the paragraph.
What if we want to be able to change a value dynamically?
Writing Javascript inside {} allows us to run Javascript functions and methods.
We can see it as a separator between Javascript and HTML.

const title = "Random Number"
function randomNum() {
  return Math.floor((Math.random() * 10) + 1)
}

const myNum = (
  <div>
      <h1>{title}</h1>
      <h2>My number is: {randomNum()}</h2>
  </div>
)

ReactDOM.render(myNum, document.getElementById("root"))

Enter fullscreen mode Exit fullscreen mode

Now, the <h1> will get updated when we change the title. And whenever we refresh the page, a random number will be generated.

Important Notes:
Whatever comes inside {} should be a Javascript expression.

Conclusion

  • JSX is a syntax that allows us to type an HTML-like code directly in Javascript.
  • Basic rules of JSX:
    • Have an explicit closing tag: <p></p>.
    • Self-closed: <input />.
    • Have a wrapper when there are many JSX elements; <></> or <div></div>
    • Writing Javascript inside {} allows us to use Javascript logics in JSX. And the logic inside {} should be a Javascript expression.

Thank you for reading!
Last but not least, you can find me on Twitter. Let's connect! 😊

Discussion (9)

Collapse
thenerdydev profile image
The Nerdy Dev

Awesome Article, Ayu !

Just curious about how you marked down those pink boxes at the start and the bottom of your post (the indexing of the series).

Collapse
adiatiayu profile image
Ayu Adiati Author

Thanks for reading! 😃

Before you publish the article, click the hexagon (next to save) button and add your article to a series that you want.
The series and indexes will be generated by itself after you have at least 2 articles in the series.
I hope this helps 😊

Collapse
thenerdydev profile image
The Nerdy Dev

Thank you ! Got it. 😊

Collapse
ayush123 profile image
Ayush

nice post

Collapse
adiatiayu profile image
Ayu Adiati Author

Thank you 🙂

Collapse
shaharafat profile image
Md. Shah Arafat

Nice one. Keep sharing.

Collapse
adiatiayu profile image
Ayu Adiati Author

Thank you 😊

Collapse
bam92 profile image
Abel Lifaefi Mbula

Thank you for sharing this great post. I've written a similar post last year. You can find it there 👇

abelmbula.com/blog/understanding-jsx/

Collapse
adiatiayu profile image
Ayu Adiati Author

Thank you for reading 😊
One nice post you have there too! Thank you for sharing

Forem Open with the Forem app