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:
I am having difficulty in understanding how the code in App.css gets used/imported in index.js?
Actually, You want to know, how the CSS code written in App.css
is applied to App
Component. The answer is straight forward, It is because your App.js
is using that CSS file since App.css
is imported in your App.js
file
`import "./App.css";`
All the CSS is first being applied to App
Component and only when you import and Render App
in index.js
using
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
React renders your App
component along with all the CSS that is provided in App.css
.
Now addressing your other statment:
Afterall only App is getting exported (as default) which is not visibly using
any CSS code inside it.
Well I have to say, this is not a right statement as App
Component is using CSS written in App.css
. In your JSX you have returned the following:
<div className="App">
<h1>Hello</h1>
</div>
You see className="App"
, so App
here is your class selector
and the CSS for this is this.
.App {
text-align: center;
color: blue;
}
Try using any other CSS property here and you will see the changes reflecting.