5

Let's say I have a React component that gets the Tailwind class name from props for example :

import React from "react";

export default function Header({navColor}) {

  return (
    <nav
    className="flex justify-center items-center text-white  text-xl h-14"> //I want to add a class that it's name is the (navColor) value to the nav tag 
      TEST
    </nav>
  );
}

How can achieve this?

4

2 Answers 2

6

You can use Template literals to achieve that

Use ${} inside backticks ``

<nav
    className={`flex justify-center items-center text-white  text-xl h-14 ${navColor}`}> 
      TEST
</nav>
Sign up to request clarification or add additional context in comments.

Comments

1
import classNames from "classnames";
import React from "react";

export default function Header({ navColor }) {
  const headerClass = classNames(
    "flex justify-center items-center text-white text-xl h-14",
    navColor,
  );
  return <nav className={headerClass}>TEST</nav>;
}

classNames is also one of good option. You don't have to worry about misadding whitespace.

2 Comments

Not much need for classnames dependency when we can use template literals as above answer.
@CodeFinity Penguin's point is, not worrying about whitespaces. That's a big headache. Thats what classnames is solving. Not every dependency is heavy. Its a minimalistic function github.com/JedWatson/classnames/blob/main/index.js Thats all

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.