简体   繁体   中英

Set Dropdown value based on Browser Language ReactJS?

So i have a small setup in which i have a dropdown and the Dropdown has two values. I am trying to set the default value of the dropdown based on the browser language detected. So if the Browser language is English, the dropdown and it's value should default to English and if the Language is Spanish then it should default to Spanish and so on. Essentially it should be dynamic and it might grow more into the Future. Any help will be Appreciated.

Check out this CodeSandbox for a working example.

This is the complete Code

import React, { Component } from "react";

class Newbie extends Component {
  state = {
    languageSelection: [
      { option: "English", value: "en-us" },
      { option: "Spanish", value: "es" }
    ]
  };
  componentDidMount() {
    let detectedLanguage = navigator.language || navigator.userLanguage;
    alert("The Language is " + detectedLanguage)
  }

  render() {
    return (
      <div>
        <label>
          Language
          <select>
            <option value="en-us">English</option>
            <option value="es">Spanish</option>
          </select>
        </label>
      </div>
    );
  }
}

export default Newbie;

Thank you for all the assistance guys.: Much appreciated. :)

import React, { Component } from "react";

class Newbie extends Component {
  state = { selected: navigator.language || navigator.userLanguage };

  handleChange = (e) => {
    this.setState({ selected: e.target.value })
  }


  render() {
    return (
      <div>
        <label>
          Language
          <select value={this.state.selected} onChange={this.handleChange}>
            <option value="en-US">English</option>
            <option value="es">Spanish</option>
          </select>
        </label>
      </div>
    );
  }
}

export default Newbie;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM