Nested elements

Using JSX markup is useful for describing UI structures that have parent-child relationships. For example, a <li> tag is only useful as the child of a <ul> or <ol> tag—you're probably going to make similar nested structures with your own React components. For this, you need to use the children property. Let's see how this works. Here's the JSX markup:

import React from 'react';
import { render } from 'react-dom';

// Imports our two components that render children...
import MySection from './MySection';
import MyButton from './MyButton';

// Renders the "MySection" element, which has a child
// component of "MyButton", which in turn has child text.
render(
<MySection>
<MyButton>My Button Text</MyButton>
</MySection>,
document.getElementById('root')
);

You're importing two of your own React components: MySection and MyButton. Now, if you look at the JSX markup, you'll notice that <MyButton> is a child of <MySection>. You'll also notice that the MyButton component accepts text as its child, instead of more JSX elements. Let's see how these components work, starting with MySection:

import React, { Component } from 'react';

// Renders a "<section>" element. The section has
// a heading element and this is followed by
// "this.props.children".
export default class MySection extends Component {
render() {
return (
<section>
<h2>My Section</h2>
{this.props.children}
</section>
);
}
}

This component renders a standard <section> HTML element, a heading, and then {this.props.children}. It's this last construct that allows components to access nested elements or text, and to render it.

The two braces used in the preceding example are used for JavaScript expressions. I'll touch on more details of the JavaScript expression syntax found in JSX markup in the following section.

Now, let's look at the MyButton component:

import React, { Component } from 'react';

// Renders a "<button>" element, using
// "this.props.children" as the text.
export default class MyButton extends Component {
render() {
return <button>{this.props.children}</button>;
}
}

This component is using the exact same pattern as MySection; take the {this.props.children} value, and surround it with meaningful markup. React handles the messy details for you. In this example, the button text is a child of MyButton, which is, in turn, a child of MySection. However, the button text is transparently passed through MySection. In other words, we didn't have to write any code in MySection to make sure that MyButton got its text. Pretty cool, right? Here's what the rendered output looks like:

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

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