Search code examples
cssreactjssassjsxtsx

Access HTML by id through SASS


Is there a possibility to access an HTML element by id through SASS? I use SASS in combination with React in TSX files. Normally for styling I would define a SASS entry and add that entry to the list of classes, as shown in the following example:

Report.sass:

.city {
    color: red;
}

Report.tsx:

import * as React from "react";
import * as Style from "./Report.scss";

export class Report extends React.Component<{}, {}> {
    public render() {
        return <div className={Style.city}>Test text for cities</div>;
    }
}

This example works perfectly fine. But if I now gave the div tag an id, I would need to also change the SASS file accordingly. This through fails, as shown here:

Report.sass:

#city {
    color: red;
}

Report.tsx:

import * as React from "react";
import * as Style from "./Report.scss";

export class Report extends React.Component<{}, {}> {
    public render() {
        return <div id="city">Test text for cities</div>;
    }
}

I believe that the SASS file forgets about the #city entry as there is no pointer in the Report.tsx to it. Am I right with this assumption? How could I make the SASS command work with the city id?


Solution

  • I think theres some misunderstandings about css and html.

    You can have both a class and id tag for each html element.

    Therefore it will compile fine if you have the following:

    <div id="NewYork" className={Style.city}>
    

    This is an unorthodox way to apply styles in React though. The easier way is to import the stylesheet via

    import './Report.scss';
    

    then you can use your styles more freely like so:

    <div id="NewYork" className="city">