Search code examples
reactjseventsdrop-down-menuonchangearray.prototype.map

onChange event won't fire in .map function React


I cannot get this onChange event to fire? The goal is to render multiple options from a drop down, from some data I have, then console log "hello" when any of the options is clicked...

It doesn't seem to want to let me use onChange or onClick events in my rendered option elements. If i can simply console log first , then i can figure out everything else. I only posted the necessary code but I can post the rest if needed!

const SlideData = [
  {
    title: "Slide 0",
  },
  {
    title: "Slide 1",
  },
  {
    title: "Slide 2",
  },
];

export default SlideData;
let options = SlideData.map((item, index) => (
    <option
      key={index}
      value={index}
      onChange={() => {
        console.log("hello");
      }}
    >
      {item.title}
    </option>
  ));
 <select className={styles.select} onChange={goto}>
          <option>--Select--</option>
          {options}
 </select>

Solution

  • goal was to pass the index and console log it technically. so I guess this worked for me

    const slideRef = useRef();
    const goto = ({ target }) => {
        slideRef.current.goTo(parseInt(target.value, 10));
        console.log(target.value);
      };
    
      const options = SlideData.map((item, index) => (
        <option key={index} value={index}>
          {item.title}
        </option>
      ));
    
    return (
        <div className={styles.container}>
          <Slide ref={slideRef} {...properties}>
            <div className={styles.slide}>First Slide</div>
            <div className={styles.slide}>Second Slide</div>
            <div className={styles.slide}>Third Slide</div>
            <div className={styles.slide}>Fourth Slide</div>
            <div className={styles.slide}>Fifth Slide</div>
          </Slide>
          <div>
            <Button type="button" onClick={back}>
              Back
            </Button>
            <Button type="button" onClick={next}>
              Next
            </Button>
            <select className={styles.select} onChange={goto}>
              <option>--Select--</option>
              {options}
            </select>
          </div>
        </div>
      );