In this tutorial, you will learn several tips and tricks that will help you write cleaner ReactJS code. The aim of these refactorings is to make your life easier while debugging. Unless you are a complete ReactJS newbie, you will know that rendering HTML in ReactJS applications is done using JSX. JSX looks similar to HTML and the end result is HTML. While JSX looks like HTML it is not. There are some fundamental differences. If you are not aware of these differences then you will likely waste many hours in frustration wondering why your application is behaving in a way that you did not intend it to! If you want to make your life a little easier when using React, then read on.
What is JSX?
class is a reserved keyword, - used for creating classes. In HTML, the keyword
class as this would confuse the process. In React, to set a CSS selector onto a component you would use the
className attribute instead. When you encounter these differences in React then there are usually good solid technical reasons why they have changed things. The React team haven't change the
class modifier just for shits and giggles. Understanding this point is essential in order to understand some of the reasons why React has been built the way it has.Let us say you wrote this JSX in a component:
Things To Consider When Using JSX
class you will need to use
className. Instead of using
for you use
<>, or, you can wrap your HTML with a unused
Spacing : As your JSX gets transpiled, the spacing in your component may not work the same way as it would in normal HTML:
In HTML putting a space between elements will add a space to it. In React this would be ignored. Instead, you could add a space, this way:
Booleans : In JSX booleans can trip you up at the time. In the code below, what do you think will happen?
As we have covered, due to JSX being converted into HTML, there are a few subtle differences you need to be aware. JSX gives you a number of benefits and for such a small trade-off, it's pretty easy.