0

I have a Card looks like this

    <Card.Header style={room.roomCapacity === room.students.length ? {backgroundColor: "#DC4C64"} : room.students.length === 0 ? {backgroundColor: '#14A44D'} : {backgroundColor: '#E4A11B'}} className={"text-center CardHeader"}>{room.roomNumber}</Card.Header>
    

But I want to write all styles in css. So how can i implement style={} function into css with these conditions?

1 Answer 1

1

You could use a memoization function with useMemo to get the correct color based on your conditions.

import { useMemo } from 'react';

const ExampleComponent = ({ room }) => {
  const isRoomFull = room.roomCapacity === room.students.length;
  const isRoomEmpty = room.students.length === 0;

  const backgroundColor = useMemo(() => {
    if (isRoomFull) {
      return '#DC4C64';
    }

    if (isRoomEmpty) {
      return '#14A44D';
    }

    return '#E4A11B';
  }, [isRoomFull, isRoomEmpty]);

  return (
    <Card.Header 
      className="text-center CardHeader"
      style={{
        backgroundColor
      }} 
    >
      {room.roomNumber}
    </Card.Header>
  );
};
Sign up to request clarification or add additional context in comments.

Comments

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.