2

I need your help !

I'm on a project for my compagny and I should create a select field that can be duplicate with React. So, I have a little problem when I want to save my selection, if I refresh the page, the default option still the same (and not the selected one). There is my code for select.js:

import React, { Component, PropTypes } from 'react';

class Select extends React.Component {

  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(data) {
    this.setState({value:data.value});
  }

  render() {
    return (
        <label>
          <select className="widefat" name={this.props.name} onChange={this.handleChange}>
            <option value="grapefruit">Grapefruit</option>
            <option value="lime">Lime</option>
            <option value="coconut">Coconut</option>
            <option value="mango">Mango</option>
          </select>
        </label>
    );
  }
}

export default Select;

I change the default value :

When i change the select option

After a refresh

I think it's because in select.js It initialize the value to '' and don't save the selection but I don't know how to save the selection.

3
  • Use localStorage for it or if you people are using redux-storage you can save the value in redux store . redux-storage will save the value for you in session storage Commented Nov 29, 2017 at 9:42
  • How did you implement this in my code ? Sorry but I never use React redux ans I discover react 3 days ago. thx Commented Nov 29, 2017 at 9:59
  • Ok so , use localStorage API to set value. In constructor, you can define the initial State. Read through the localStorage documentation developer.mozilla.org/en-US/docs/Web/API/Window/localStorage Commented Nov 29, 2017 at 10:02

3 Answers 3

9

Here's a way to accomplish this:

import React, { Component, PropTypes } from 'react';

class Select extends Component {

  constructor(props) {
    super(props);
    this.state = { value: props.value }; // can be initialized by <Select value='someValue' />
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  render() {
    return (
        <label>
          <select className="widefat" value={this.state.value} name={this.props.name} onChange={this.handleChange.bind(this)}>
            <option value="grapefruit">Grapefruit</option>
            <option value="lime">Lime</option>
            <option value="coconut">Coconut</option>
            <option value="mango">Mango</option>
          </select>
        </label>
    );
  }
}

export default Select;

Going further

You could iterate in a map in the render method to implement this like so:

  render() {
    const dictionary = [
      { value: 'grapefruit', label: 'Grapefruit' },
      { value: 'lime', label: 'Lime' },
      { value: 'coconut', label: 'Coconut' },
      { value: 'mango', label: 'Mango' }
    ];

    return (
        <label>
          <select
            className="widefat"
            value={this.state.value}
            name={this.props.name}
            onChange={this.handleChange}
          >
            {dictionary.map(
              // Iterating over every entry of the dictionary and converting each
              // one of them into an `option` JSX element
              ({ value, label }) => <option key={value} value={value}>{label}</option>
            )}
          </select>
        </label>
    );
  }
3
  • Your both answers doesn't work for me. I have this warning : Commented Nov 29, 2017 at 10:01
  • Warning: Use the defaultValue or value props on <select> instead of setting selected on <option>. Commented Nov 29, 2017 at 10:01
  • 1
    I updated my answer. In fact, it's simpler this way (thanks to the react warning, I learned something new today)
    – 3Dos
    Commented Nov 29, 2017 at 10:07
0

The target event property returns the element that triggered the event. It stores a lot of properties, print it to the console, that would familiarize with its capabilities

import React, { Component } from 'react';

class Select extends Component {

  constructor(props) {
    super(props);
    this.state = { value: '' };
  }

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

  render() {
    return (
     <label>
       <select className="widefat" name={this.props.name} onChange={this.handleChange}>
        <option value="grapefruit">Grapefruit</option>
        <option value="lime">Lime</option>
        <option value="coconut">Coconut</option>
        <option value="mango">Mango</option>
      </select>
    </label>
    );
  }
}

export default Select;
3
  • 1
    Code only answers to dont explain a solution. Please go ahead and explain yourself, why and how you solve the problem and what OP might have done wrong or missed out. Commented Nov 29, 2017 at 9:59
  • Then this is probably your place to go: Stack Overflow based on the russian lanuage. Since the normal Stack Overflow is English only, please avoid any russian language and try to speak english or switch to the linked website. Commented Nov 29, 2017 at 10:09
  • Thanks for the advice, but I'll decide where I stand :)
    – Pablo
    Commented Nov 29, 2017 at 10:11
-1

After a long journey to search in documentation and in the depth of internet I found my answer. I forgot to add a "for" for my label. There is my final code :

    import React, { Component, PropTypes } from 'react';

class Select extends React.Component {

  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event) {
    this.setState({value: this.props.value});
  }

  render() {
    return (
        <label htmlFor={this.props.id}>{this.props.label}
          <select defaultValue={this.props.value}  id={this.props.id} className="widefat" name={this.props.name} onChange={this.handleChange.bind(this)}>
            <option>Aucun</option>
            <option value="55">Option 2</option>
            <option value="126">Backend configuration & installation</option>
            <option value="125">Frontend integration</option>
            <option value="124">Graphic Design</option>
          </select>
        </label>
    );
  }
}

export default Select;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.