Kadie
Kadie

Reputation: 1

How to change the Font Weight of a SelectValue component in React when a SelectItem is selected?

I'm using a custom Select component in a React application, which includes SelectValue and SelectItem components. I want to change the font weight of the SelectValue component to bold when a SelectItem is selected.

For example, a user clicks the "TO:" option in the dropdown, so the placeholder of the SelectValue component changes from "Select" to "TO:"; I need the font of the placeholder to change from normal to bold in this case.

Here's a simplified version of my code:

import { useState, useEffect } from 'react';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "src/components/ui/select";

export const LinkCard: React.FC = () => {
  const [isSelected, setIsSelected] = useState(false);

  useEffect(() => {
    console.log('isSelected:', isSelected);
  }, [isSelected]);

  return (
    <Select>
      <SelectTrigger>
        <SelectValue key={isSelected.toString()} placeholder="Select" style={{ fontWeight: isSelected ? 'bold' : 'normal' }}/>
      </SelectTrigger>
      <SelectContent position="popper">
        <SelectItem value="filterTo" style={{ fontWeight: 'bold' }} onClick={() => { console.log('SelectItem clicked'); setIsSelected(true); }}>TO:</SelectItem>
        {/* other SelectItem components */}
      </SelectContent>
    </Select>
  );
};

I'm using a useState hook to keep track of whether a SelectItem has been selected, and I'm trying to use this state to change the font weight of the SelectValue component. However, the onClick handlers on the SelectItem components are not being triggered, so the isSelected state is not being updated.

I've tried adding onClick and onChange handlers to the Select component, but I get a TypeScript error saying that these props do not exist on the Select component.

Upvotes: 0

Views: 35

Answers (1)

Evan
Evan

Reputation: 33

This question is incomplete. We need to know what you use for styling in order to give you more guidance.

If you use css for it, you can have a look at the focus pseudo-class. It is generally triggered, when the user clicks or taps on an element or selects it with the keyboard's Tab key. :focus

label {
  display: block;
  margin-top: 1em;
}

input:focus {
  background-color: lightblue;
}

select:focus {
  background-color: ivory;
}
<form>
  <p>Which flavor would you like to order?</p>
  <label>Full Name: <input name="firstName" type="text" /></label>
  <label
    >Flavor:
    <select name="flavor">
      <option>Cherry</option>
      <option>Green Tea</option>
      <option>Moose Tracks</option>
      <option>Mint Chip</option>
    </select>
  </label>
</form>

Upvotes: 0

Related Questions