October 22, 2024
Chicago 12, Melborne City, USA
CSS

How to apply styling to a component and all its descendants in React/Next.js?


Let’s say I have a Next.js/React project with one top-level component and many child and grand-child components. In the grand-child components there are div elements with classNames only including Tailwind’s classes ( e.g. className ="flex justify-between" etc). Is there a way to style all the div elements having some particular combination of Tailwind classes that are contained within the top level component or within its descendants, without applying the styles globally or changing the code for every individual div?

This is an illustration of the structure:

import ChildComponent from './ChildComponent';

export default function ParentComponent() {
  return (
    <div>
      <h1 className="text-2xl font-bold mb-4">Parent Component</h1>
      <div className="space-y-4">
        <ChildComponent number={1} />
        <ChildComponent number={2} />
      </div>
    </div>
  );
}
import GrandChildComponent from './GrandChildComponent';

export default function ChildComponent({ number }) {
  return (
    <div>
      <h2 className="text-xl font-semibold mb-2">Child Component {number}</h2>
      <div className="space-y-2">
        <GrandChildComponent number={1} />
        <GrandChildComponent number={2} />
      </div>
    </div>
  );
}
import styles from '../styles/styles.module.css';

export default function GrandChildComponent({ number }) {
  return (
    <div>
      <h3 className="text-lg font-medium mb-1">Grandchild Component {number}</h3>
      <div className="space-y-1">
        {/* Bottom-level divs with the same Tailwind classes */}
        <div className="flex grow bg-blue-100 p-2">Item A</div>
        <div className="flex grow bg-blue-100 p-2">Item B</div>
        <div className="flex grow bg-blue-100 p-2">Item C</div>
      </div>
    </div>
  );
}

Essentially, I need to style some particular type of div (there is plenty of them) on a page and I’m trying to find a way to do this with least amount of changes to the code-base (I can’t switch to generating the divs using .map or forEach etc inside the JSX) and without a lot of manual work. The answer can use a completely different approach than the one implied by the question as long as there isn’t a lot of changes to the code and/or loops in JSX.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video