Brandons404
Brandons404

Reputation: 149

How can I update a field from changing something in a "select" tag in react?

I am pretty new to React, and I feel like I am close but cannot seem to figure this out. I want to change the value of some text in one element (Field), by selecting an option in another (Set).

I have 3 javascript files: "App", "Field", and "Set". Here is the code I have:

App looks like this:

import React, { useState } from "react";
import Field from "./Field";
import Set from "./Set";

export default function App() {
  const [region, setRegion] = useState("all");

  function set_region(region) {
    setRegion(region);
  }

  return (
    <div className="App">
      <Set update={set_region} />
      <Field region={region} />
    </div>
  );
}

Field looks like this:

import React from "react";

export default function field({ region }) {
  return <p>{region}</p>;
}

And Set looks like this:

import React from "react";

export default function Set(set_region) {
  function update() {
    set_region(this.value);
  }

  return (
    <div>
      <select onChange={update}>
        <option value="all">All</option>
        <option value="car">Carolinas</option>
        <option value="florida">Florida</option>
      </select>
    </div>
  );
}

The current error reads "set_region is not a function". I know you cant do this but I just want to portray my goal as best I can. After updating the useState somehow with the dropdown, I want to make the field text update to the new value. Also, "this.value" returns undefined, so I am not sure what to use there. Do I even need useState for this?

Thank you in advance.

Upvotes: 0

Views: 66

Answers (2)

Ali
Ali

Reputation: 1759

You're using the select in a wrong way.

Use npm to install react-select.

import Select from 'react-select';
const [region, setRegion] = useState("all");
const regions= [
    {
        'value':'value 1',
        'label':'value 1',
    },
    {
        'value':'value 2',
        'label':'value 2',
    }
]
const update= (_selectedOption) => {
  set_region(_selectedOption)
}


 return (
    <div>
       <Select
          placeholder='Select Region'
          value={region}
          onChange={update}
          options={regions}
        />
    </div>
  );

Upvotes: 1

aleEspinosaM
aleEspinosaM

Reputation: 444

the issue here is that you are passing to Set a update function as a prop so you can destructure that property and call it as <select onChange={update}>

then on your APP component you need to recieve the event so you can change it like

  function set_region(e) {
    setRegion(e.target.value);
  }

i have set up a codesandbox so you can play around

https://codesandbox.io/s/vigilant-heyrovsky-c9uy4?file=/src/App.js

also i recomend passing down the setRegion function from useState instead of creating a new one :D

Upvotes: 2

Related Questions