I am new to react (Javascript as well), I got this doubt reagarding the output when rendering the React Component-> App
of the template code generated using 'create-react-app'.
Here is the App.js:
import React from "react";
import "./App.css";
export function App() {
return (
<div className="App">
<h1>Hello</h1>
</div>
);
}
export default App;
App.css:
.App {
text-align: center;
color: blue;
}
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
serviceWorker.unregister();
File directory system :
.
├── node_modules
├── package.json
├── package-lock.json
├── public
│ ├── favicon.ico
│ ├── index.html
│ ├── logo192.png
│ ├── logo512.png
│ ├── manifest.json
│ └── robots.txt
├── README.md
└── src
├── App.css
├── App.js
├── App.test.js
├── index.css
├── index.js
├── serviceWorker.js
└── setupTests.js
In the file App.js
, export default App;
exports App
which is then being imported in index.js
which uses ReactDOM.render
to render the App
. I am having difficulty in understanding how the code in App.css
gets used/imported in index.js
? Afterall only App
is getting exported (as default) which is not visibly using any CSS code inside it. Am I missing or interpreting something wrong here?
Thanks for reading.
Edit :
Specifically, I want to know how does React applies CSS (which are imported) to the components defined in a script?
Coming to your statement:
Actually, You want to know, how the CSS code written in
App.css
is applied toApp
Component. The answer is straight forward, It is because yourApp.js
is using that CSS file sinceApp.css
is imported in yourApp.js
fileAll the CSS is first being applied to
App
Component and only when you import and RenderApp
inindex.js
usingReact renders your
App
component along with all the CSS that is provided inApp.css
.Now addressing your other statment:
Well I have to say, this is not a right statement as
App
Component is using CSS written inApp.css
. In your JSX you have returned the following:You see
className="App"
, soApp
here is yourclass selector
and the CSS for this is this.Try using any other CSS property here and you will see the changes reflecting.