2

I am trying to use the Dropdown element of Semantic UI React. It is meant to work with a REST API that allows to get a list of movies. React is configured to fetch data from the appropriate REST API application (this already works for other elements of the frontend).

I would like to get the list of movie names as options. Please have a look at the following JS snippet.

import React, { useState, useEffect } from "react";
import { Dropdown } from "semantic-ui-react";

export const MovieDropdown = () => {
  const [movie, setMovie] = useState("");
  const [movieOptions, setMovieOptions] = useState([]);

  useEffect(() => {
    fetch("/movies")
      .then((response) => response.json())
      .then((data) =>
        setMovieOptions(
          data.map((x) => {
            return { key: x.name, text: x.name, value: x.name };
          })
        )
      );
  }, []);

  return (
    <Dropdown
      placeholder="Select Movie"
      search
      selection
      options={movieOptions}
      onChange={(e) => setMovie(e.target.value)}
    />
  );
};
export default MovieDropdown;

I could not figure it out from https://react.semantic-ui.com/modules/dropdown/#usage-remote.

1 Answer 1

1

Your code looks good. Change a small thing and it will work:

onChange={e => setMovie(e.target.value)} // you cannot use event in setState. furthermore checkout the second param of the onChange-Event

to

onChange={(e, {value}) => setMovie(value)}

checkout fixing-react-warning-synthetic-events-in-setstate

here's the full working code

import React, { useState, useEffect } from "react";
import { Dropdown } from "semantic-ui-react";

export const MovieDropdown = () => {
  const [movie, setMovie] = useState("");
  const [movieOptions, setMovieOptions] = useState([]);

  useEffect(() => {
    fetch("/movies")
      .then((response) => response.json())
      .then((data) =>
        setMovieOptions(
          data.map((x) => {
            return { key: x.name, text: x.name, value: x.name };
          })
        )
      );
  }, []);

  return (
    <Dropdown
      placeholder="Select Movie"
      search
      selection
      options={movieOptions}
      onChange={(e, {value}) => setMovie(value)}
    />
  );
};
export default MovieDropdown;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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