Using Vanilla CSS with React?

This is my first time working on a react app and I'm a bit unsure of the best approach to styling components. Currently, I am creating a separate .css file for each component or page, and including it implicitly. While this method seems the simplest, I am aware that there are some drawbacks. I'm not sure if this is considered a bad practice. Should I be using styled components/css modules instead, or does it not make a significant difference in the end?

Answer №1

If you're deciding between styled components and vanilla CSS (with BEM), choose the one that best suits your needs.

I have experience with both and believe that both have their merits, but there are some distinctions between them.

For instance, if you need to use variables throughout all components (such as themes), styled components require you to use ThemeProvider and then consume it like this:

const FancyDiv = styled.div`
    background: ${props => props.theme.colors.main)``;

On the other hand, with vanilla CSS, you need to import a CSS file in each component's CSS file, like this in SCSS:

// src/components/fancyDiv/styles.scss

@import '../../styles/settings.scss';

.fancyDiv {
    background: $main-color;
}

Another difference arises when you need to style an element based on props or state. Consider a scenario where you want to style a navigation link based on whether it is active or not.

const [isActive, setIsActive] = useState(false);

Using styled components:

const FancyLink = styled.a`
    color: ${props => props.isActive ? 'red' : 'green'}`;

<FancyLink href="#aboutme" isActive={isActive}>About me</FancyLink>

With vanilla CSS:

.nav__link--active {
    color: 'red';
}

<a href="#aboutme" className=`nav-link ${isActive ? 'nav__link--active' : ''}`>About me</a>

Both approaches have their strengths and can be suitable for various situations, albeit in slightly different ways.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to turn off the auto-complete feature for JavaScript keywords in HTML within JSX in WebStorm?

While using WebStorm, I've noticed that it automatically completes JavaScript keywords as I type regular text in JSX. This behavior is starting to frustrate me because I have to constantly press ESC or click elsewhere to hide the auto-complete popup. ...

Nested data selection in React

I have been experimenting with creating a nested select optgroup and attempted the following: const data = [ { sectorId: 5, sectorName: "Sector One", departments: [ { deptName: "Production", jobtitles: [ { ...

Leverage JavaScript to customize the appearance of existing links within an external HTML document

Forgive me for my lack of expertise in Javascript. I will do my best to explain clearly. On my website, I have an external html file for the navigation menu that is loaded with javascript to simplify editing (so I don't need to update nav elements on ...

Navigate to a specific section of a webpage with automatic scrolling

I'm developing a Chrome App and incorporating the web view tag, which functions similarly to an iframe. Is there a way to load a webpage inside the web view halfway down the page? I have attempted the following: application.js: $(document).ready(f ...

Trouble persisting values with Heroku due to variable issues

Here is a concise example: let value = null; const getValues = () => { fetch('/third-party-api') .then(res => res.json()) .then(data => { value = data; }) } getValues(); app.get("/values", async (req, res) ...

Issue with Material UI: Unable to utilize import statement outside of a module due to Select dependency

Hello there! Here is my query: I am currently working on a project using NextJS + React with node. Everything seems to be running smoothly, except for one issue I encounter when reloading a page with a Select component from Material UI. The relevant code ...

Using Angular 6 to import GeoJSON into a Leaflet map

I am facing an issue while trying to import a GeoJson file into Leaflet in my Angular app version 6. Although the geojson is being successfully drawn on the leafletmap, I am encountering an error that is preventing me from building my app. Is there anyone ...

Troubleshooting MaterialUI: Is there a way to prevent the InputLabel text from disappearing when setting a background color on the Select component?

My goal is to change the background color on dropdown elements while keeping the default text visible. Currently, if I don't explicitly set a background color on the Select component, the text specified in the InputLabel displays correctly. However, o ...

Showing a series of JavaScript countdowns consecutively

I am working on a project where I want to display a second countdown after the first one finishes using meteor. The initial timer code looks like this: sec = 5 @timer = setInterval((-> $('#timer').text sec-- if sec == -1 $('#time ...

What is the best way to eliminate all frames from the current windows using jQuery?

When transitioning to another page from my center frame, I need to ensure that the top and bottom frames are not visible in the new page. This will prevent my spinner or footer from showing up on the page I'm navigating to. Is it possible to achieve ...

Tips for resolving validation errors when adding to MongoDB in a MERN application

Currently, I am in the process of mastering the MERN stack by developing a straightforward shopping list application. My API is set up to handle GET, POST, and DELETE requests successfully, as confirmed through Postman testing. Locally, I can retrieve it ...

Having trouble sending a POST request with body parameters in Node.js? The error "undefined req.body.param" might be popping up when you're

I've encountered an issue with my server.js code: const bodyParser = require('body-parser'); const cors = require('cors'); const morgan = require('morgan'); var express = require('express') , http = requir ...

Form-check radio buttons within the form-check-inline class of Bootstrap 4.1.1

I am attempting to showcase a radio button as an inline option. According to the Bootstrap 4.1.1 documentation, the example code is: <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="inlineRadioOption ...

I have been attempting to execute 'npm run build' for my React application using Tailwind CSS, but it keeps displaying errors

Here is the error thrown in the terminal: > craco build C:\Users\kaund\OneDrive\Documents\codinglife\project-dreams\react-projects\order-form\node_modules\@craco\craco\lib\loaders.js:34 ...

Selecting an object from JSON data with Angular using $routeParams

I am attempting to showcase information from a JSON file that is structured like this: [ { "category":"category1", "link":"category1", "expand":false, "keyword":"category1, category1 online, category1 something" }, { "category":" ...

How can we display data from the database in a table if the data is stored as a string separated by commas using Ajax?

I am having trouble displaying 33 and 123 of heading 1 and heading 2 in a new row. Can someone please help me with this issue? Even though I updated the code, the for loop is only showing the last value. $.ajax({ type:"POST", url:"{{route(&ap ...

The webpack command in the terminal failed to locate the file /config/webpack/development.js

Whenever I type $ webpack in my terminal, I encounter the following error: webpack config /Users/kristenmkulha/Desktop/react-help-queue/config/webpack/development.js not found, please run 'bundle exec rails webpacker:install' to install ...

Is there a problem with Chrome's display?

I'm currently using Chrome version 53.0.2785.143 and have noticed a rendering issue that tends to occur more frequently within my application when utilizing CSS transform scale. Feel free to check out this JSFiddle link which demonstrates the problem ...

When adjusting the month/year, the Material Date Picker extends beyond its container

Currently, I have an Angular 18 application with a page that includes a material date picker component. When I open the Date Picker, everything displays correctly. However, when I try to change the month using the left/right arrow or the year, the data co ...

What is the best way to add a new element with specified text to a group of chosen HTML elements?

Here is some HTML code that selects specific elements: let array = jQuery.makeArray($(".dersprg tr td:nth-child(6)")); The selected elements contain table header text and some irrelevant data. While I can interpret the irrelevant data using if statements ...