Tutorial on nesting React components
In the last tutorial, we created the Greeting component. Continuing directly from that, we now create a PictureBox component that has an image as well as Greeting component inside it. Like this…
1. First we need to refactor out the Greeting class from the app.jsx into its own greeting.jsx in the src directory like this …
Note that because it is now a stand-alone file, we need to add the require(‘react’) to indicate that it will need the react module. We also changed it so that the createClass output is assigned to module.exports so that other modules can use it.
2. In particular, the app.jsx class references greeting.jsx with a require statement that contain the relative path. We need the “./” even if greeting is in the same directory, so that it does not try to look for it in the node_modules directory. The app.jsx becomes …
3. Re-build and run to see that everything works as before.
4. Now we write it in a separate file “picturebox.jsx” in the “src” directory like this …
It is going to need React and Greeting, so hence the two require statements. In its render, we output a wrapping div with a CSS class of “panel”. But in JSX we can not use “class” because it is a reserved word to indicate an React class, therefore we have to use “className” in the place of where we normally would use CSS “class”.
Within the wrapping div, we embed the Greeting component by writing it like a HTML tag. Remember to close that tag (JSX is kind of strict about that). But the Greeting component requires us to pass it a name value, we pass it via an attribute of the same name. this.props.name will be the value of whatever is passed to the PictureBox via the options object in the app.jsx
As before, the output of this class is saved to modules.exports.
5. We changed app.jsx to require the PictureBox and ask it to be rendered passing to it the options object…
6. At this time, the index.html should run without any errors in the Javascript console. However, we do want to add some styling for panel in our index.html …
And maybe add an image in our PictureBox class …
So that we get something looking like this …