React + TypeScript: Handling Select onChange Event

Last updated on August 5, 2021 A Goodman Loading... Post a comment

A select element is a drop-down list with multiple options. In this article, we will examine an end-to-end example of handling the onChange event of a select element in a React web app that written with TypeScript.

The Example

App Preview

What we are going to build is a simple web app that has a select element in the center of the screen. When a user chooses one option from the drop-down list, the selected value will be displayed.

The Complete Code

1. Create a new project with the command below:

npx create-react-app kindacode_example --template typescript

2. Replace all of the default code in your src/App.tsx (or src/App.ts) with the following:

// App.tsx
// Kindacode.com
import React, { useState } from "react";

const App: React.FunctionComponent = () => {
  const [selectedOption, setSelectedOption] = useState<String>();

  // This function is triggered when the select changes
  const selectChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
    const value = event.target.value;
    setSelectedOption(value);
  };

  return (
    <div style={styles.container}>
      <select onChange={selectChange} style={styles.select}>
        <option selected disabled>
          Choose one
        </option>
        <option value="blue">Blue</option>
        <option value="red">Red</option>
        <option value="green">Green</option>
        <option value="yellow">Yellow</option>
        <option value="kindacode.com">Kindacode.com</option>
      </select>
      {selectedOption && <h2 style={styles.result}>{selectedOption}</h2>}
    </div>
  );
};

export default App;

// Just some styles
const styles: { [name: string]: React.CSSProperties } = {
  container: {
    marginTop: 50,
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
  },
  select: {
    padding: 5,
    width: 200,
  },
  result: {
    marginTop: 30,
  },
};

3. Run the project and go to http://localhost:3000 see the result:

npm start

Conclusion

You’ve learned how to handle the onChange event of a select element in React and TypeScript. If you would like to explore more new and interesting stuff about modern frontend development, take a look at the following articles:

You can also check our React topic page and Next.js topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles