skip to Main Content

I have a custom select option component, and an array with data that I pass to this component, but I need to make an optional attribute with which I can pass styles for the option tag. In this case, I need to pass a unique font-family for each option tag.

But I get an error:

The style prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + ’em’}} when using JSX.

Here is the code:

App.js

const fonts = [
     { label: 'Arial', value: 'Arial', style: `font-family: Work Sans', sans-serif;` }
]

<Select options={fonts} value={ChooseFontForSideBorder} onChange={event => setChooseFontForSideBorder(event.target.value)} />

Select.jsx

export function Select({value, options, onChange}) {
    return (
        <select className="w-100" value={value} onChange={onChange}>
          {options.map((option, i) => (
            <option 
              key={`option-${i}`}
              value={option.value}
              style={option.style}
            >
              {option.label}
            </option>
          ))}
        </select>
    );
 };

2

Answers


  1. Chosen as BEST ANSWER

    I solved it this way:

    const fonts = [
         { label: 'Arial', value: 'Arial', font: 'Arial' },
    ]
    
    ...
    <option 
         key={`option-${i}`}
         value={option.value}
         style={option.font ? {fontFamily: option.font} : null}
    >
    ...
    

    But it's a very crooked solution. And I want to be well practiced at it!

    Can anyone show me a better solution? Thanks!


  2. inline style accepts an object as params with style-property so you need to fix the style in your fonts variable like so

    Solution:
    App.js

    const fonts = [
         { label: 'Arial', value: 'Arial', style:{fontFamily: "'Work Sans' sans-serif" }
    ]
    
    <Select options={fonts} value={ChooseFontForSideBorder} onChange={event => setChooseFontForSideBorder(event.target.value)} />
    
        
    

    Select.jsx

        export function Select({value, options, onChange}) {
        return (
            <select className="w-100" value={value} onChange={onChange}>
              {options.map((option, i) => (
                <option 
                  key={`option-${i}`}
                  value={option.value}
                  style={option.style}
                >
                  {option.label}
                </option>
              ))}
            </select>
        );
     };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search