Can you use normal CSS with React? - reactjs

I'm using create-react-app and have read bad things about inline styles so I wanted to use css modules however they aren't supported by create-react-app at this time. Can I literally just use plain old css in one big file? Also with this approach how do I style a react component. For example I have a component and I give it a class name: <card className="cardStyle" />. Why does this not work? I want to bed able to position it just like I would a div.

it's certainly possible, you may have plain old CSS classes in a style.css somewhere, but you'll have to make sure your app includes it,
e.g. have in your App.js
import './style.css'

The standard way is to do the following;
import React, { Component } from 'react';
import './Button.css'; // Tell Webpack that Button.js uses these styles
class Button extends Component {
render() {
// You can use them as regular CSS styles
return <div className="Button" />;
}
}
See: https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#adding-a-stylesheet

Using CSS Modules might be better way:
CSS Modules have .module.css in their file name, like styles.module.css. Naming it so is important it avoids serious issue in plain CSS when having same CSS class names in different CSS files.
File : styles.module.css
.myClass1 {
background-color: red;
}
File : App.js
import styles from'./styles.module.css';
<div className={styles['myClass1']} >
some content
</div>
By default supported by Create React App - https://reactjs.org/docs/create-a-new-react-app.html
This can done using simple steps
npx create-react-app my-app
cd my-app
npm start
Links:
. https://create-react-app.dev/docs/adding-a-css-modules-stylesheet/
. https://www.freecodecamp.org/news/how-to-style-react-apps-with-css/
If you want to use normal css but want more flexibilities like props to css, and open to install more dependencies then alternatives are:
. https://emotion.sh/docs/introduction
. https://styled-components.com/
Some are migrating styled-components to emotion, so may be emotion is better way to start with.
See https://storybook.js.org/blog/541-components-from-styled-components-to-emotion/

Related

Other component styles are getting applied to the component which I have not imported

Hello I am working on simple crud application in react js 18.0.0. My problem is I have my own styles for one component say eg..Home. But the styles which I have used for other components is also getting applied to Home component even though I did not imported it. Can anyone explain why?
I have attached an image for your reference.
In the above image I was in home component. But if you see the styles the container class in forgetPassword.css and login.css is also getting applied in home component. but In home component I did not imported those two css files(forgetPassword.css and login.css)
Yes this is because by default react does not support css or styles.
you can either use css modules(https://create-react-app.dev/docs/adding-a-css-modules-stylesheet/)
Or
Use styled components.
I suggest you to try the css modules as that will be beginner friendly and easy.
You need to move your css to seperate file and name it [filename].module.css
In your case Home.module.css
Then in your Home.js component import it like import styles from './Home.module.css'
Then in your component use it like
<div className={styles.container} > ... </div>
I also recommend you not to modify the original bootstrap classes, instead create your custom class and add the overrides there.
eg:
<div className={`${styles.container} ${styles.home-container}`} > ... </div>

How to import SCSS on Component Level with Next.js

I am coming from a CRA background and working my way through Next.js version 9.4.2
My project tree looks something like this :-
pages/
_app.tsx
index.tsx
components/
Navbar/
index.ts
Navbar.tsx
Navbar.scss
Inside my Navbar.tsx I have a statement import './Navbar.scss';
This gives me the following error :-
./src/components/Navbar/Navbar.scss
Global CSS cannot be imported from files other than your Custom <App>. Please move all global CSS imports to src/pages/_app.tsx.
Read more: https://err.sh/next.js/css-global
Location: src/components/Navbar/Navbar.tsx
The error, as mentioned, goes away if I move the import Navbar.scss statement to pages/_app.tsx
I know I can switch to Navbar.module.scss, but I don't want to go down the route of modular scss as I expect my scss to get complex I would like to stick to the manner in which I write my scss and not keep finding work arounds to issues that might arise later. I am open to being convinced here but I have not found good read ups on this to choose it as my path.
So by the looks if it, I am stuck with importing all <component>.scss files in _app.tsx. This will leave me with a long list of <component>.scss imports in my _app.tsx and I will also be left with a lot of <component>.scss files for Components that might conditionally not render.
What are my options here ?
Your Navbar.scss file is not named properly.
Let's say your stylesheet contains something like...
$color: red;
.someclassselector {
color: $color;
}
Component stylesheet files have to be named in the following convention for next.js to compile them as addressed in next's css getting started guide
<TheComponent>.module.scss
be imported like this:
import styles from './<MyComponent>.module.scss>';
and be applied to the component like this:
<TheComponent className={styles.someclassselector} />
Not really an expert but it seems that you should stick to class selectors as global selectors can only be declared if you import them in pages/_app.js. You may name a main.scss file to use Global or Tag Element selectors like h1 {},h2{}, * {}, etc.

React How to generate a separate stylesheet for a specific component?

Here I want to generate a separate stylesheet for Landing component and hopefully for other. Other components will have Hero component too. Can anyone tell me how can I do that?. Is it a good idea?.
Anything with an underscore _name.scss, tells your sass compiler that it's a partial scss file. Simply don't use an underscore for single component scss files, for example: Hero.scss. Then in your Hero.js, you can import the style like so:
import './Hero.scss';
<div className="heroContainer">...</div>
or, if your webpack has been configured to allow scss module imports, then you could do:
import { heroContainer } from './Hero.scss';
<div className={heroContainer}>...</div>
If you want to share heroContainer's styles with other stylesheets, simply use the #extend in your scss file.
clientsContainer {
#extend .heroContainer;
}
The downside to this approach is that you'll have to manually import any partials, like _vars.scss, _mixins.scss...etc, and any other dependent stylesheets into each new Example.scss file.
Ideally, if you're working in a large team, it's better to individualize your scss stylesheets, so that everything is modular (components and their styles can be passed off to someone else, instead of having to send ALL of your stylesheets for ONE component).

How to use SCSS variables into my React components

I am working on a React project that follows this structure
src |
components |
Footer |
index.jsx
styles.scss
Header |
index.jsx
styles.scss
scss |
helpers.scss
variables.scss
...
main.scss
Into my variables file I was using the css custom variables so, all them where on :root and I can access them in my components styles.
When I wanted to create the dark colours I wanted to use the SCSS function darken, but it does not evaluate them and throws an error saying that var(--blue) is not a valid colour.
As a solution I decided to move all the variables into a SCSS variables but when project is building it throws another error that says that a $blue is not defined.
The unique solution possible I can use, it is to include the variables file in all the styles files but, I do not know if there are a better solution for the structure that I am using.
From React 17
To access your scss variables into the react component, you need to do something like that
Install node-sass as a dependency or dev dependency
No need to do any config change in webpack
import as a module <-- main point
variables.module.scss
$color: skyblue;
$primaryColor: red;
:export {
color: $color;
primary-color: $primaryColor;
}
App.js
import variables from '<YOUR_PATH>/variables.module.scss';
const App = () => {
console.log(variables);
}
If you don't want to use styled-component
then you can follow this link.
https://til.hashrocket.com/posts/sxbrscjuqu-share-scss-variables-with-javascript
I use a similar structure to organize my .scss files. I like having the styles in the same folder as the component. However, I import all scss files to my main.scss file. This helps avoid style conflicts in the DOM.
main.scss
import "./scss/helpers.scss"
import "./variables.scss"
import "./Footer/style.scss"
import "./Header/styles.scss"
Make sure to name your files with an underscore so that all the files get merged on compilation. Note you don't need to name the underscore in the import.
_helpers.scss
_variable.scss
_style.scss
Using this method you only need to import styles once into your app. index.jsx
There are different ways I can recomend you to tackle this.
1- Duplicate the values of those variables. Add them both on your variables.scss and as constants in some other file, maybe config.js or constants.js that way you'll be able to reference these values from your react components, the downside to this, is you'll have to remember to change them in two places if you have to modify the value.
2- Consider using styled-components. With styled components you can define your styles within your components, using variables or props within the styles.
3- Use some mechanism to define these variables in a single file or as environment variables, and setup your build process to be able to import these values into js and scss files.
It is possible to use custom variables with that project structure using css-vars mixin.
After proposing the option to evaluate custom variables before executing the SCSS function, a guy suggested me this mixin. I have just tested and works pretty nice.

How to structure the css files in reactjs in a way that it follows the concept of component separation

I have a question,
I am working on a project which is written in react.
Everything is based on component in react so based on my understanding everything including css files should be defined in a related component itself this way if we remove the component from the project every related file will be removed so far so good.
However consider this case:
.size{
font-size:20px;
}
as you can see there are many cases as above which can be used in different components. So we want to put all the css files into the related components then we should either replicate the same css definition in different places or for these kind of scenarios we can have a shared folder out of the components. Is there any rule or guideline how to structure the css files in a react project in the right way?
I'm not sure if there is any established way to organized shared css but let me offer some observations.
If you have an App component that imports an App.css. Any of the components used within this app will have access to the class's set in App.css.
// app.css
.test {
color: red;
}
// app.js
import './app.css';
class App extends Component {
render() {
return (
<App>
<MyComponent />
</App>
);
}
}
// my-component.js
class MyComponent extends Component {
render() {
<div className='test'>
this text is red.
</div>
}
}
If you have a css file imported in MyComponent that has a style that conflicts with the one passed from App then the MyComponent style will replace ALL uses of the style.
To put in short, it doesn't matter where your css lives. Putting css into the same place as components is just way we try to keep things organized but at the end of the day the whole app has access to all css. And from the example we can tell that latter definitions of the style replace earlier definitions.

Resources