Search code examples
reactjscanvasreact-selectselect-options

how can i store font family into an array and use it in select options in react.js


Actually, I want an array of font family so that I can use it in select options. On the basis of select options I want to change the font of text input field.

import React from "react";
import ReactDOM from "react-dom";
import Select from "react-select";

import "./styles.css";



const styles = {
  control: base => ({
    ...base,
    fontFamily: "Times New Roman"
  }),
  menu: base => ({
    ...base,
    fontFamily: "Times New Roman"
  })
};

function App() {
  return (
    <div className="App">
      <Select className="select" styles={styles}  >
     <option> Times Roman </option>
</Select>
    </div>
  );
}

Solution

  • You need to save the selected font in the state, then pass the state in the styles.

    import React,{useState} from "react";
    import ReactDOM from "react-dom";
    import Select from "react-select";
    
    import "./styles.css";
    
    
    
    const styles = {
      control: base => ({
        ...base,
        fontFamily: stateStyle
      }),
      menu: base => ({
        ...base,
        fontFamily: stateStyle
      })
    };
    
    function App() {
    const [stateStyle,setStateStyle] = useState("some font")
      return (
        <div className="App">
          <Select className="select" styles={styles}  >
         <option onChange={() => setStateStyle("Times New Roman")}> Times Roman </option>
    </Select>
        </div>
      );
    }