Steve Breese

A Chicago-based Full-stack JavaScript Developer

React Web 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.

  1. 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. Existing component with too much HTML
  2. Create new JS file in the components directory with a name that describes the purpose of the div. Create new JS file in the components directory with a name that describes the content
  3. Populate the new component with required component code. This includes:
    • react import statement
    • stateless functional component
    • component export statement
    Important! Be sure the file name and the component name are the same. Populate the new component with required code.
  4. Cut div JSX from the overloaded component. Cut & paste the div JSX from the overloaded component to the new component.
  5. Paste it into the new component. Existing component with too much HTML
  6. Copy all dependencies of the cut JSX code from the overloaded component to the new component. Copy (do not cut) any dependencies of the JSX 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.
  7. Paste the copied dependencies between the react import statement and the JSX functional component. Paste copied dependencies above the JSX in the new component
  8. Add an import statement and tag to pull in the broken out component into the original file. Add refereces to the new component into the previously overloaded component.
  9. Test your code.

Performing the above steps repeatedly as the need arises will keep your code clean, dry and more reliable.