Encapsulating HTML

The reason that you want to create new JSX elements is so that we can encapsulate larger structures. This means that instead of having to type out complex markup, you can use your custom tag. The React component returns the JSX that replaces the element. Let's look at an example now:

// We also need "Component" so that we can
// extend it and make a new JSX tag.
import React, { Component } from 'react';
import { render } from 'react-dom';

// "MyComponent" extends "Compoennt", which means that
// we can now use it in JSX markup.
class MyComponent extends Component {
render() {
// All components have a "render()" method, which
// retunrns some JSX markup. In this case, "MyComponent"
// encapsulates a larger HTML structure.
return (
<section>
<h1>My Component</h1>
<p>Content in my component...</p>
</section>
);
}
}

// Now when we render "<MyComponent>" tags, the encapsulated
// HTML structure is actually rendered. These are the
// building blocks of our UI.
render(<MyComponent />, document.getElementById('root'));

Here's what the rendered output looks like:

This is the first React component that you've implemented, so let's take a moment to dissect what's going on here. You've created a class called MyComponent that extends the Component class from React. This is how you create a new JSX element. As you can see in the call to render(), you're rendering a <MyComponent> element.

The HTML that this component encapsulates is returned by the render() method. In this case, when the JSX <MyComponent> is rendered by react-dom, it's replaced by a <section> element, and everything within it.

When React renders JSX, any custom elements that you use must have their corresponding React component within the same scope. In the preceding example, the MyComponent class was declared in the same scope as the call to render(), so everything worked as expected. Usually, you'll import components, adding them to the appropriate scope. You'll see more of this as you progress through the book.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.181.52