Introduction to React
JSX
JSX is a syntax extension for JavaScript and lets you put HTML into your Javascript and run Javascript in your HTML. React does not actually require JSX, but it is a lot easier to write React with JSX than without. This video briefly explains what JSX is:
Code example: JSX where HTML is embedded into Javascript
const element = <h1>Hello, world!</h1>
Code example: JSX where Javascript is embedded in HTML.
const greeting = “Hello, world!”const element = <h1>{greeting}</h1>;
When transpiled the javascript in the {brackets} will be executed and result in “Hello, World”. Through JSX, you can combine HTML and Javascript in the same file in an intuitive way. Babel will then compile the JSX code into plain Javascript code.
Code example: Creating multiple elements with JSX
One of the great things with JSX is that it makes it simple to create multiple HTML elements at the same time by embedding the Javascript map function in HTML.
function ListOfCountries() {let scandinavianCountries = ['Norway','Sweden','Denmark','Iceland','Finland',]return (<ul>{scandinavianCountries.map(country => {return <li> {country} </li>})}</ul>)}
As you can see in the code example above we first create an unordered list <ul> and then we execute the javascript map function inside of the {brackets}.
This map function then returns a list item <li> for each country in the list, and again we use the {brackets} to run javascript and get the value of the country variable.
Even though it may seem like it, JSX doesn't actually create transpile into raw HTML. Actually it goes through an extra step and creates React Elements. Knowing exactly how this transpiling works isn't necessary to create React applications so we will just briefly cover it in the next section.