Ways to implement CSS in React

Let us look at the ways to implement CSS Modules in React and Next.js

Define your CSS classes in a file like this:

/* styles.module.css */
.container {
  font-size: 20px;
  border: 1px solid #000;
  border-radius: 5px;
}
.title {
  color: red;
}

And then import it in your component like this:

// app/page.js
import styles from './styles.module.css'

export default function Page() {
  return (
    <div className={styles.container}>
      <h1 className={styles.title}>Hello, World!</h1>
    </div>
  )
}

How to combine two css classes from your CSS module?

This syntax will help you with that.

className={`${styles.btn} ${styles.btnReset}`}

How to delare CSS as JSX style?

function Error() {
  return (
    <>
      <p className="error">
        <span>💥</span> There was an error fecthing data.
      </p>
      <style jsx>{`
      .error{
        text-align: center;
        font-size: 1.6rem;
        font-weight: 500;
        padding: 2rem;
        background-color: #495057;
        border-radius: 10px;
      }
      `}</style>
    </>
  );
}

export default Error;

How do I do conditional CSS rendering with CSS modules in React?

Consider you have a stylesheet module like this.


Then you component or element will look like this.

  <button
    className={`${styles.btn} ${styles.btnOption} ${index === answer ? styles.answer : ''} ${hasAnswered ? (ans.key === 1 ? styles.correct : styles.wrong) : ''
      }`}
    key={ans.content}
    disabled={hasAnswered}
    onClick={() => dispatch({ type: 'newAnswer', payload: index })}
  >