Creating CSS-in-JS Components in React JS without External Stylesheet interference

import React, { Component } from "react";
import './navbar.css'


class NavBar extends Component {


  render() {
    return (
      <div>

          navbar content



      </div>


    );
  }
}

export default NavBar;

If I were to include NavBar in another file and display it.

import React, { Component } from "react";
import NavBar from './NavBar'
import './differentfile.css'


class somefile extends Component {

  render() {
    return (
      <div id="test">

          <NavBar />


      </div>


    );
  }
}

export default somefile;

How can I isolate the CSS styling for my navbar? I want to use components without having the CSS from other files affect them.

differentfile.css

#test div {
    text-align: left;
}

^ This code aligns all div elements under #test to the left

Answer №1

When considering the impact of CSS files on a website, it ultimately depends on how they are written. If other CSS files use general rules such as element matches, preventing conflicts entirely may not be possible. However, there are ways to minimize these conflicts.

  • One approach is to follow BEM (Block Element Modifier) for your styles, which can be found at . This method creates tighter and more specific styles for your components.
  • Another option is to utilize css in js libraries like styled-components, available at . This allows you to create strong CSS rules that often take precedence over conflicting rules from other sources.

Personally, I have transitioned from using BEM to implementing css in js with styled-components for most of my recent projects, and I have found this approach to work effectively in managing CSS conflicts.

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

Filtering function that works without specific knowledge of keys

I'm working on a JavaScript method to filter a list dynamically without knowing the specific key (s). I've made some progress, but I'm stuck and not sure how to proceed. The foreach loop I have isn't correct, but I used it for clarity. ...

Flowtype: Utilizing type hints for class-based higher order component

I am currently working on typehinting a higher-order component (HOC) that adds a specific prop to a passed Component. The code snippet looks like this: // @flow import React, { Component } from 'react'; import type { ComponentType } from 'r ...

Warning issued by npm during compilation: The template string expression is unexpected as there should be no curly braces in the

Getting an npm warning during compiling (Unexpected template string expression no-template-curly-in-string) import React from 'react'; const Card = ({name, email, id }) => { return ( <div className='tc bg-light-green dib b ...

Adjusting the "lang" attribute to modify the font style

By using the HTML lang attribute and setting it to "en", I noticed that some of the div fonts and colors were changing to the default ones in Bootstrap. Although I am utilizing the Bliss2 Regular font, the default font style seems to be taking precedence. ...

"Hovering over one div does not trigger the display of another div

I seem to have forgotten my CSS skills, but I am facing an issue. Here is the code snippet: <div class="footer_container"> <div class="website_logo_to_footerexpand"></div> <div class="info_cont"> <div class ...

Reactjs encountering issues loading css file

Currently, I am working on a project in Reactjs with Nextjs. To add CSS to my project, I have stored my CSS files in the 'styles' folder. In order to include them, I created a file called '_document.js' and implemented the following cod ...

Retrieving a collection of nested objects from an API, iterating through three cycles, sharing thoughts on ReactJS

When working with data fetched from an API in the parent component, which is an array of objects, I find myself having to map three times in order to render the necessary information in the child component. Here are some questions that I have: 1) Is ther ...

Is there a way to incorporate margins into a React component using TypeScript?

I am currently facing a challenge in passing CSS attributes to a component that I am working with. The reason behind this is that I need to modify the margins to fit a specific space, hence my attempt to directly pass the margins. Does anyone have any sug ...

Styling the background of the endAdornment in a material-ui textfield using React

I tried following the instructions from this source: Unfortunately, the example code provided doesn't seem to be functioning properly now. Is there a way to achieve the same result without having that right margin so that it aligns better with the r ...

Align the responsive image in the center of a container

I am facing a challenge in centering an image wrapped by an anchor tag inside a div. I have tried using display flexbox and justify-content:center for the image, which works to some extent. However, the height of the image remains constant while the width ...

Using Typescript for testing React components: successfully passing an array of objects as props

My current approach involves passing an array of objects to mock component data for testing: const mockPackage = { id: '1232-1234-12321-12321', name: 'Mock Package', price: 8.32, description: 'Mock description', glo ...

Guide on consolidating all React production build files into a single root folder while ensuring directory tree is not maintained in the static folder

This is my first experience working with IPFS in conjunction with React. After reviewing the reactjs examples, it seems that the code to deploy the website itself does not differ from a non-IPFS-based site. According to the hosting documentation I am usi ...

Is server-side rendering necessary for `browserHistory` in React Router?

I am a beginner in the world of React and currently diving into the complexities of routing. While hashHistory (/#/paths/like/this) proves to be functional, browserHistory (/paths/like/this) appears much cleaner. However, I noticed that when reopening URLs ...

Enhance the appearance of the popover by incorporating an arrow-like element for dismissing the

Here is some code I want to modify: https://i.stack.imgur.com/0C61Y.png I would like to add an arrow element at the top, similar to this: https://i.stack.imgur.com/pDT3s.png This will give it a popup-like appearance. Below is the CSS styling for the co ...

The image I want to show is invisible on the CSS custom radio button

I'm having trouble creating a custom radio button that displays the image I want. The current setup doesn't seem to be working as expected. label { font-weight: lighter; cursor:pointer; } input[type="radio"] { display:none; } in ...

Struggling to interact with a field within an HTML/CSS LESS document

I have encountered an issue with my website where I am unable to click on certain fields or buttons within the Login fieldset. Strangely, I can only interact with the fields and buttons located within the Register fieldset. The CSS for my website is writt ...

Utilizing a .svg file in Material-UI Avatar component: A step-by-step guide

Trying to incorporate an svg file into the mui avatar component has posed a challenge for me. When I use <Avatar src="./**.svg" />, it does not render and appears as blank. However, using <Avatar src="./**.png" /> works pe ...

The justify-content: space-between property does not work in a nested flex box scenario

I'm currently working on styling a cart in Angular and facing an issue with aligning the price all the way to the right of the cart. I attempted using `space-between` within the outer div, which worked fine, but when applied to the inner div, it doesn ...

Issue: The code mentioned below is functioning perfectly during development, but once it is deployed on Heroku, it exhibits sporadic behavior

Struggling to make socket.io function properly on Heroku, encountering issues with code inconsistency between development and deployment. The problem persists even after uploading to Heroku: 1. No unusual activity in the logs. 2. Data saved to the databa ...

What is the best way to retrieve a specific item from an array of objects stored in JSON format using React?

I have received a json file named data.json which contains multiple objects in an array. My goal is to extract the value of a specific key from each object. To achieve this, I am utilizing react redux to fetch these values and present them in a table forma ...