React Tutorial: Breaking out a div into its own Component
When developing a React application, you will often find that you need to use a particular block of JSX (that funny tag syntax that is neither a string, nor HTML) in more than one place. At this point, any developer who follows the don't repeat yourself (DRY) principal will need to breakout the JSX (often a div element) into its own React component. The following are instructions on how to do this.
- Identify the div that needs to be in its own component. In this example, the first child div under the parent div prints out a list of all ingredients from an API. It needs to be used on another page of the app, so we will break it out into its own component.
- Create new JS file in the components directory with a name that describes the purpose of the div.
- Populate the new component with required component code. This includes:
- react import statement
- stateless functional component
- component export statement
- Cut div JSX from the overloaded component.
- Paste it into the new component.
- Copy all dependencies of the cut JSX code from the overloaded component to the new component.
Review the original component's remaining JSX to determine whether the copied dependencies can be deleted from the original file.
- Paste the copied dependencies between the react import statement and the JSX functional component.
- Add an import statement and tag to pull in the broken out component into the original file.
- Test your code.
Performing the above steps repeatedly as the need arises will keep your code clean, dry and more reliable.