index.css vs. App.css in default app created by "create-react-app" -- what's the difference?

Reactjs

Reactjs Problem Overview


It seems like index.css would be more for global styles and App.css would be for the App component only - but isn't the App component normally also my whole app? What's the best practice here?

Reactjs Solutions


Solution 1 - Reactjs

The App component is essentially the top most component in a React-based application, from whom all other components are children of. So in create-react-app, the reason why there's an App.css and an index.css is just so that create-react-app can have a very simple directory structure and no naming conflicts between "App.css" and "index.css", so you spend less time removing generic stuff and more time building your stuff instead. The best practice for structuring a React-based app is to just have each component in it's own separate directory with its own index.js file, index.css file and something like index.test.js or however you want to structure your test files. "Index.js" is the first file looked for in a directory when you call an ES6 import statement for that directory, so you can write:

import HUD from './HUD'

instead of:

import HUD from './HUD/HUD.js'

So using index.css just helps to make clear that this index.css file is for this Component, since this index.js only refers to this Component

Here's a basic React application directory structure:

src
├── App
│   ├── HUD
│   │   ├── index.css
│   │   ├── index.js
│   │   └── index.test.js
│   ├── index.css
│   ├── index.js
│   ├── index.test.js
│   ├── Maze
│   │   ├── index.css
│   │   ├── index.js
│   │   └── index.test.js
│   ├── Tile
│   │   ├── index.css
│   │   ├── index.js
│   │   └── index.test.js
│   └── TouchControl
│       ├── index.css
│       ├── index.js
│       └── index.test.js
├── index.css
└── index.js

A src level index.css file would be a good place to put top-level container DOM element CSS style rules, since the src level index.js is the initial place in a React-based application where you tell React to physically mount the App Component to the actual HTML DOM, on a container element, something like this and say that 'root' is an ID of an element already on the page before your JavaScript loads:

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import './index.css'

ReactDOM.render( <App />, document.getElementById('root'))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCP SeanView Question on Stackoverflow
Solution 1 - ReactjsStephen CollinsView Answer on Stackoverflow