- Organizing Your React application
In Part 1 of the two-part series by Carlos Santana Roldan, you learned how to create your React component. Now, in this Part 2 of the series, you’ll learn how to organize your React application. The author of the article, Carlos Santana Roldan, is the founder of Codejobs and a React Technical Lead at Disney ABC Television Group.
Organizing your React application
You can create React components with the default structure that create-react-app provides, but in this article, you’ll see a better way to organize the project so that you are ready for when the application grows.
- You need to create a new React app (check Part 1 of this series if you haven’t created a React app yet).
- Currently, your React application directory tree looks like this:
- Now, create src/components and src/shared directories.
- After this, create the src/components/Home directory for your component and move Home.js into this folder.
- The App.js file stays at the src/components level.
- Also, App.css and App.test.js will stay at the src/components level.
- Move the logo.svg file to src/shared/images.
- Your index.js will stay at the src/ level.
- Now your directory tree should look like this:
It is highly recommended that you create another directory for shared components, src/shared/components. In the App.js file, change the logo and Home imports:
import logo from '../shared/images/logo.svg'; import Home from './Home/Home';
- After you changed this, you need to open index.js and fix the import path for the App component:
import App from './components/App';
This new structure will give you more flexibility to group your React components smartly. With this new structure, you’ll be able to create sub-components if you need them, and this is very important when developing complex applications with React.
If you found this article interesting, you can explore Carlos Santana Roldan’s React Cookbook to be on the road to becoming a React expert. React Cookbook has over 66 hands-on recipes that cover UI development, animations, component architecture, routing, databases, testing, and debugging with React.