Smit
Smit

Reputation: 41

Is there any way to export/pass a state variable to an external CSS file in ReactJS

const Dropdown = ({ options, selected, onSelectedChange }) => {
    const [ open, setopen ] = useState(false);


    const renderedOptions = options.map((option) => {
        if (option.value === selected.value) {
            return null;
        }

        return (
            <div key={option.value} className="item" onClick={() => onSelectedChange(option)}>
                {option.label}
            </div>
        );
    });

    return (
        <div className="ui form">
            <div className="field">
                <label className="label">Select a color</label>
                <div onClick={() => setopen(!open)} className={`ui selection dropdown ${open ? 'visible active' : ''}`}>
                    <i className="dropdown icon" />
                    <div className="text">{selected.label}</div>
                    <div className={`menu ${open ? 'visible transition' : ''}`}>{renderedOptions}</div>
                </div>
            </div>

            //Here is the selected.value state (value contains string of color name
            {<div style={{ color: `${selected.value}` }}>{selected.value}</div>}
        </div>
    );
};

export default Dropdown;

const options = [
    {
        label: 'The Color Red',
        value: 'red'
    },
    {
        label: 'The Color Green',
        value: 'green'
    },
    {
        label: 'The Color Blue',
        value: 'blue'
    }
];

How can I use the selected.value in an external CSS file?

The data in the selected.value is a string of color name(s).

Upvotes: 3

Views: 805

Answers (4)

Laureline
Laureline

Reputation: 187

Another way using CSS stylesheet.
Usually when I need to pass a value to use it for CSS I'll
go for specific CSS classes as I rather use the stylesheet
for style ( !== style within component ) for scalability reasons &
ease to access. If it can help ...

  • I. Known values case / no need to convert into word
    to expect ( seems like it should be either [ blue,red,green ])

      <div className = { selected.value } />
    
  • II. Need to convert into word
    Let's say you need to change a selected.value that could be an hexadecimal value, you'll need to associate a word className you could use for CSS later on.
    This is just an example and you can do a lot more within the expression passed

      // convert anticipated value to the word you need
      const colors = {'#F00': 'red', '#0F0' : green, '#00F': 'blue'};
    
      <div className = { colors[ selected.value ] } />
    
  • 📌Applied example

      import './style.css' // style.css as same level of your component
    
      const Dropdown = ({options,...}) => {
        // if need to make wording *(cf:. case )
        // const color = {'#F00': 'red', '#0F0' : green, '#00F': 'blue'};
    
        //...
        return (
            //...
            // if need to make wording *(cf:. case )
            // <div className = { colors[ selected.value ] }> { selected.value } </div> */ }
            <div className = { selected.value }> { selected.value } </div>
         )
        }
    

CSS for the above cases.

/*CSS file: style.css*/
.red { ...code... }
.green { ...code... }
.blue { ...code... }

Upvotes: 0

Smit
Smit

Reputation: 41

Here is how I solved it by using concept from this URL

import styles from './colorchange.css';

//...

//For setting default value (and closing dropdown when clicked outside)
useEffect(() => {
        document.body.addEventListener('click', (event) => {
            if (ref.current.contains(event.target)) {
                return;
            }
            setopen(false);
        });

        document.documentElement.style.setProperty(`--variablename`, selected.value);
    }, []);

//...

//inside renderedoption
return (
            <div
                key={option.value}
                className="item"
                onClick={() => {
                    onSelectedChange(option);
                    document.documentElement.style.setProperty(`--variablename`, option.value);
                }}
            >
                {option.label}
            </div>
        );

//....
//for printing the color
<div className="colorcolor">This text is: {selected.value}</div>

CSS FILE:

 {
    --variablename: default;
}

.colorcolor {
    color: var(--variablename);
}


Upvotes: 1

Kimimomo
Kimimomo

Reputation: 105

You can probably use Styled Components if that's what you're looking for, just an example, not really well thought out. The component can be in another file

const HoveredLink = styled.span`
    color: ${props => props.selected ? 'black' : 'rgb(150, 153, 156)'};
`

<HoveredLink selected={\\someconditionhere} > Hover me <HoveredLink/> 

Upvotes: 1

Mike Kokadii
Mike Kokadii

Reputation: 513

You can simple use as a variable, this is not exactly CSS. So this one should work:

<div style={{color: selected.value}} >{ selected.label } </div>

You can also set style as a new variable:

const Dropdown = ({options,...}) => {
    const styleDiv = {
        color: options.value
    }
    //...
    return (
        //...
        <div style={styleDiv}> {options.label} </div>
    )
}

Upvotes: 0

Related Questions