We created a country component at the end of our previous tutorial on creating a first React component and it rendered as we expected. However, we wrote a lot of code to create a simple component.
Getting Started with JSX
The best way to get you familiarized with JSX is to convert the code of our
Country component from the previous tutorial into JSX. Here is the original code that we wrote:
function Country(props) return React.createElement('div', className: "container" , React.createElement('h2', className: "country-name" , `Country Name: $props.name`), React.createElement('p', className: "capital" , `Capital: $props.capital`), React.createElement('p', className: "population" , `Population: $props.population`));
We can write it as follows with the help of JSX:
function Country(props) return ( <div className="container"> <h2 className="country-name">Country Name: props.name</h2> <p className="capital">Capital: props.capital</p> <p className="population">Population: props.population</p> </div> );
We can now render our
Country component inside the browser by using the following code:
let countryElement = ( <Country name="United States" capital="Washington, D.C." population="332 million" /> ); let rootElement = document.getElementById("root"); ReactDOM.createRoot(rootElement).render(countryElement);
Try adding information about the area of the United States to this component. You will find it is much easier to do so with JSX.
Important Things to Remember
There are a few rules that you need to keep in mind when working with JSX.
1. It’s XML, not HTML!
I would like to repeat that the code we wrote above might look like HTML but it is actually XML. This means that you will have to follow rules of XML when composing the component structure. This means you need to close every element that you add to the component. Elements with children will need to have an opening and a closing tag. Elements which don’t have any children will require self-closing tag.
2. Double Quotes != Single Quotes
Attribute values that have strings need to use double quotes. This is the reason we used double quotes when specifying the value of the
className attribute above.
Country component when we accessed values like capital and population.
4. Tags are Case-Sensitive
Regular HTML elements need to have lowercase tags. This means that we couldn’t use
Div instead of
div element by specifying it all in lowercase.
4. Watch Out for Reserved Keywords in JSX
You cannot use reserved keywords inside the JSX you are writing. This is why we had to use
className to specify the value of
class attribute. Similarly,
for is a reserved keyword so we will need to use
htmlFor in order to specify a value for the
for attribute in HTML.
5. One Element at a Time
return statement that you write for your components can only return one element. The element itself can have multiple children. This is why we returned a single container