Is there a way to style an element in React using the ID without using className?

Viewed 12912

I am converting an old website into React, and do not want to have to change all the CSS files that were previously coded. A lot of elements have their styles set currently by using an id. Is there a way to get className={styles["#topBar"]} to set the style correctly without having to delete the # and replacing it with a . in the CSS folder?

1 Answers

Since you are using CSS Modules you need to access the styles slightly differently. You need to import styles from 'Component.module.css'; and then declare your styles by referencing this imported object styles.MyClass or in your case since you have hyphens you need to use bracket notation styles["top-bar"]

Here is a working sandbox

//MyComponent.js

import styles from "./MyComponent.module.css";

export default function MyComponent() {
  return (
    <div id={styles["top-bar"]}>
      <h2>My Component</h2>
      <InnerComponent id="inner" />
    </div>
  );
}

function InnerComponent({ id }) {
  return (
    <div id={styles[id]}>
      <h3>Inner Component</h3>
      <p id={styles.para}>Styled Paragraph</p>
    </div>
  );
}
//MyComponent.module.css

#top-bar {
  width: 90vw;
  margin: 1rem auto;
  padding: 1rem;
  text-align: center;
  background-color: LightPink;
}

#inner {
  background-color: LightBlue;
  text-align: left;
}

#para {
  color: red;
}

Here's a quick snippet showing it working with IDs.

function MyComponent() {
  return (
    <div id="top-bar">
      <h2>My Component</h2>
      <InnerComponent id="inner" />
    </div>
  )
}

function InnerComponent({id}) {
  return (
    <div id={id}>
      <h3>Inner Component</h3>
    </div>
  )
}

ReactDOM.render(<MyComponent />, document.getElementById('App'));
#top-bar {
  width: 90vw;
  margin: 1rem auto;
  padding: 1rem;
  text-align:center;
  background-color: LightPink;
}

#inner {
  background-color: LightBlue;
  text-align: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>


<div id="App"></div>

Related