The composite component

As we know, you can create your custom component with JSX markup and JSX syntax, and transform your component to a JavaScript syntax component.

Let's set up JSX:

<script type="text/javascript" src="js/react.min.js"></script> 
<script type="text/javascript" src="js/react-dom.min.js"></script> 
<script src="js/browser.min.js"></script> 
<script src="js/divider.js" type="text/babel"></script>

Include the following files in your HTML:

<div>
    <Divider>...</Divider>
    <p>...</p>
</div>

Add this HTML in your <body> section.

Now, we are all set to define the custom component using JSX as we have the JSX file ready to be worked on.

To create a custom component, we have to express the following mentioned HTML markup as a React custom component. You have to just follow the given example to execute your wrapped syntax/code, and in return after rendering, it will give you the expected markup result. The Divider.js file would contain:

var Divider = React.createClass({ 
    render: function () { 
        return ( 
            <div className="divider"> 
                <h2>Questions</h2><hr /> 
            </div> 
        ); 
    } 
}); 

If you want to append the child node to your component then it's possible in React-JSX. In the preceding code, you can see that we have created one variable named divider and, with the help of React-JSX, we can use it as a HTML tag as we are using defined HTML tags like <div>, <span>, and so on. Do you remember that we have used the following markup in our earlier example? If not, then please refer to the previous topic again, as it will clear up your doubts.

<Divider>Questions</Divider> 

As in the HTML syntax, here the child nodes are captured between the open and close tags in an array, which you can set in your component's props (properties).

In this example, we will use this.props.children = ["Questions"] where this.props.children is React's method:

var Divider = React.createClass({ 
    render: function () { 
        return ( 
            <div className="divider"> 
                <h2>{this.props.children}</h2><hr /> 
            </div> 
        ); 
    } 
}); 

As we have seen in the preceding example, we can create components with open and close tags the way we do in any HTML coding:

<Divider>Questions</Divider>

And we will get the expected output as follows:

<div className="divider"> 
    <h2>Questions</h2><hr /> 
</div> 
..................Content has been hidden....................

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