React: JSX & Rendering

April 30, 2019 0 Comments

React: JSX & Rendering

 

 

If you’re new to React, you’ll likely have heard about JSX, or JavaScript XML — it’s an XML-like code for elements and components. In this article, we’re going to take a look at what JSX is & why we should use it in our React applications. We’ll also take a look at what elements are, and how we can render them to the DOM.

This article is part of a series I’m writing on learning the React fundamentals. Be sure to follow me if you’d like to keep track!

As mentioned, JSX is an XML-like code which we can use when coding with React. It was developed by the team at Facebook & is mean’t to provide a more concise syntax, helping to simplify the developer experience. Let’s take a look at our first example:

const greeting = <h1>Hello, World!</h1>;

Simple, right?

What we have here is neither a String nor HTML. It’s JSX! We can use it to harness the full power of JavaScript when building our UI elements. And while it’s not mandatory, it’s certainly an extremely useful tool — it does a great job of making it clear when we’re working with UI inside of our JavaScript code.

Let’s extend our above example to include an embedded expression.

const user = 'Bob Burger';
const greeting = <h1>Hello, {user}</h1>;

ReactDOM.render(
greeting,
document.getElementById('root')
);

We use curly braces {} to embed the variable into our JSX expression. And within those curly braces we could embed any valid JavaScript expression. Such as user.firstName or printName(user) for example.

Note: We’ll look at rendering in detail later in the article, don’t be to concerned about the above render method just yet!

Let’s embed the result of a called JavaScript function:

function printName(user) {
return user.firstName + ' ' + user.lastName;
}

const user = {
firstName: 'Bob',
lastName: 'Burger'
};

const greeting = (
<h1>
Hello, {printName(user)}!
</h1>
);

ReactDOM.render(
greeting,
document.getElementById('root')
);

So whats actually going on with JSX, when we render components?

function Greeting() {
return <h1>Hello, World!</h1>
}

Each element being rendered by the Greeting component are transpiled down into React.createElement calls. The above example transpiles to:

function Greeting() {
return React.createElement("h1", {}, "Hello, World!")
}

Let’s see another example:

const greeting = (
<h1 className="speak">
Hello, world!
</h1>
);

When compiled, this code looks as follows:

const greeting = React.createElement(
'h1',
{className: 'speak'},
'Hello, world!'
);

Both of these code blocks are identical. And essentially an object is created like so:

const greeting= {
type: 'h1',
props: {
className: 'speak',
children: 'Hello, world!'
}
};

This object is known as a React element, and it functions a lot like a description of what you see on the screen. React uses these objects to build the DOM and keep it up to date.

Essentially, JSX is really just making the React.createElement(component, props, …children) function much more pleasing on the eye. Another example:

<Navbar backgroundColor = "purple" opacity = {0.8}>
Menu bar
</Navbar>

Will transpile to:

React.createElement(Navbar, {
backgroundColor: "purple",
opacity: 0.8
}, "Menu bar");

Let’s now move on the see a few more concepts…

We’ll take a deep dive into props in my next article! For now its good to remember that when building components — they’ll often render children, which require data to render correctly. The parameters we pass in are what we call props. In JSX, there are a few ways we can do this, such as:

// Defaults to "true" if no value is passed
<MyComponent connected />
// String literals passed as props
<MyComponent user= "Bob Burger" />
// Expressions (below example will evaluate to 10)
<MyComponent total = {1 + 2 + 3 + 4} />
// Spread attributes: passes the whole props object
<MyComponent selected = {...this.state} />

Note: if statements and for loops are not expressions in JavaScript, so they cannot be used in JSX directly! Instead, you could code it like so:

function NumberType(props) {
let answer;
if (props.number % 2 == 0) {
answer = <strong>even</strong>;
} else {
answer = <i>odd</i>;
}
return <div>{props.number} is an {answer} number</div>;
}

We can see our props passed into the conditional, evaluated and then returned — all via JSX.

As your apps become larger, you’ll find some components will need to render children. And then those child components will also need to render further children, and so on! With JSX, we can manage these tree-like structures of elements quite well. The rule of thumb is — whatever elements a component returns become its children.

Lets take a quick look at the ways to render child elements with JSX:

<MyComponent>I'm a child!</MyComponent>

In this very basic example, the string I’m a child is a child of MyComponent. And its accessible via props.children of MyComponent.

Say we want to return an HTML child <header>, which has two of its own children: <Nav /> and <SearchBox />. We could do this like so:

function Header(props) {
return (
<header>
<Nav />
<SearchBox />
</header>
)
}

We can also pass expressions as children, to render to our UI. This would be very useful with a to-do list app, for example:

function TodoItem(props) {
return <li>{props.content}</li>;
}

function TodoList() {
const todos = ['paint house', 'buy more chips', 'conquer world'];
return (
<ul>
{todos.map((content) => <Item key={content} content={content} />)}
</ul>
);
}

Functions can be useful when handling repetition, such as rendering repeated UI elements. We can create the structures that React will automatically render for us.

Let’s look at an example where we use a .map() function to create new pages on a website:

// Array of current pages
const pages = [
{
id: 1,
text: "Home",
link: "/"
},
{
id: 2,
text: "About",
link: "/about"
},
{
id: 3,
text: "Contact",
link: "/contact"
}
];
// Renders a <ul> which generates the <li> children
function Nav() {
return (
<ul>
{pages.map(page => {
return (
<li key={page.id}>
<a href={page.link}>{page.text}</a>
</li>
);
})}
</ul>
);
}

To add a new page to our website, we just need to add a new object to the pages array & let React handle the rest!

As I’m sure you’ve seen throughout this article, when working with JSX we’re working with elements to render into our page. An element describes what you see on the screen:

const element = <h1>Hello!</h1>;

Multiple elements such as this when combined, will form components. We’ll be taking a detailed look at components in my next article!

Typically, we’ll have a <div> like so, in our HTML:

<div id="root"></div> 

This is known as our DOM node. Everything inside of it is handled by React DOM.

And to render a React element into our root node, we pass both to ReactDOM.render(), like so:

const element = <h1>Hello!</h1>;
ReactDOM.render(element, document.getElementById('root'));

Hello! will render to our page.

Note that React elements are immutable! Once an element is created, you can’t change its children or its attributes. If if wish to update the UI, you’ll need to create a new element and pass it to ReactDOM.render().

And there we go! We’ve covered the basics of JSX and rendering. And I hope you’re beginning to see how useful these concepts are to us as developers, building React apps.

By harnessing the power of JSX to pass around elements in JavaScript, we’re building very workable code. The structure of JSX plays incredibly well with React, and despite the fact that JSX isn’t mandatory — it makes for a fantastic development experience.

I hope you found this article useful! You can follow me on Medium. I’m also on Twitter. Feel free to leave any questions in the comments below. I’ll be glad to help out!


Tag cloud