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

A guide on triggering a new chart to appear beside the adjacent <div> when a bar is clicked in a highchart

I'm a beginner with Highcharts and I have a requirement for two charts (let's call them Chart A and Chart B). Creating one chart is straightforward. What I need is, upon clicking on a bar in Chart A, a new chart (Chart B) should open next to the ...

Ways to recognize when a button has been pressed

I developed my website using the CodeIgniter framework. Here is my personal website On the homepage, if I click on the "landscape" picture (top right) or the "landscape" button in the menu, it takes me to the "landscape" page. However, when I return to t ...

Tips for downsizing a large image to fit into a smaller area

I am working on a page layout that features a small circular navigation element. However, I am facing an issue with fitting a large picture within the boundaries of this small circle without it overflowing and causing alignment problems. Does anyone have ...

Varied elevations dependent on specific screen dimensions

There seems to be a minor issue with the height of the portfolio container divs at specific window widths. The problematic widths range from 1025 to 1041 and from 768 to 784. To visualize this, try resizing your browser window to these dimensions on the fo ...

What is the procedure for inputting the settings for the export module in webpack?

I am currently working on setting up this webpack configuration file. However, I encountered an issue where the error message states that "any" is being used as a value instead of a type. How can I resolve this issue? module.exports:any = { ...

How can a block be made to stay fixed and float in a flexbox layout?

There are three blocks within the body of this page. Title bar Content block Bottom block I have employed a flex display for the body layout. My goal is to make the title bar float, meaning it should always remain at the top when scrolling. I attempted ...

Background image not displaying in new tab after Chrome extension installation

I have been developing a Chrome extension that alters the background image of a new tab. However, I have encountered an issue where the background image doesn't change the first time the extension is loaded. This problem has also occurred very occasi ...

What is the recommended return type in Typescript for a component that returns a Material-UI TableContainer?

My component is generating a Material-UI Table wrapped inside a TableContainer const DataReleaseChart = (): React.FC<?> => { return ( <TableContainer sx={{ display: 'grid', rowGap: 7, }} > ...

Optimal method for a React and HTML Select-component to output String values instead of Integer values

Within my React-class (JSX), I've included the following code: var Select = React.createClass({ onChange: function (ev) { console.log(ev.target.value); }, render: function() { var optionsHtml = this.state.options.map(function (el) { ...

The ReactJS apolloClient is unable to locate the "client" within the context or as an option provided

I'm having trouble understanding why this problem is occurring, especially since it was working fine in another application of mine. I've been trying to figure it out for the past 3 days without any luck. I came across a potential solution on st ...

Images in CSS not copied to the output directory when using Webpack

Using Webpack to bundle various javascript and css files on a website includes bundling bootstrap.css and chosen.css as part of the bundles. To achieve this, there is a main.js file serving as an entry point for importing all necessary files. The process i ...

Showing a collection of objects in a React component

**Recently started learning React and Node, and decided to fetch data into a functional component by following various tutorials. I successfully set up the server, connected it to the database, and fetched the data in React as per the tutorial instruction ...

What is causing the radio button's background color not to change after it is selected?

I've been searching and exploring various solutions, but I'm encountering some difficulties with the following scenario: There are a few restrictions: Cannot utilize Javascript or Jquery. Must be achieved using pure CSS. My objective is to chan ...

Numerous Material-UI Tooltip components that can be individually opened and closed with a click within a list

Looking for a solution: I'm working on a react component that contains a list of products. Each product has specific information that needs to be displayed in a tooltip when clicked. If you have any suggestions or solutions, please check out my code ...

Python: parsing comments in a cascading style sheet document

I am currently working on extracting the first comment block from a CSS file. Specifically, I am looking for comments that follow this pattern: /* author : name uri : link etc */ and I want to exclude any other comments present in the file, such as: /* ...

Adjust properties based on screen size with server-side rendering compatibility

I'm currently using the alpha branch of material-ui@v5. At the moment, I have developed a custom Timeline component that functions like this: const CustomTimeline = () => { const mdDown = useMediaQuery(theme => theme.breakpoints.down("md")); ...

Having issues making div elements with javascript

I am having trouble generating new divs when a specific div is clicked. Despite my efforts, nothing seems to be happening and the console isn't showing any errors. I've searched online for solutions but haven't found anything that addresses ...

Can you please tell me the font size specified as 20px/26px?

Recently stumbled upon the 20px/26px value in a codebase I'm currently working on. Wondering if anyone has encountered this before and knows what its purpose is. Interestingly, it renders with the latter pixel value (26px) in Chrome. #action { font: ...

I encountered an error while trying to synchronize my Redux state with the component state

Upon clicking the advanced sports search button, I need to display a drawer containing my API values. Currently, when mapping my Redux state with component state, an error is occurring stating "Actions must be plain objects. Use custom middleware for async ...

What is the best way to send form data to MongoDB using React?

I am seeking guidance on how to pass the values of form inputs to my MongoDB database. I am unsure of the process and need assistance. From what I understand, in the post request within my express route where a new Bounty is instantiated, I believe I need ...