Home > Mobile >  Run different functions with each select element option react
Run different functions with each select element option react

Time:12-02

I have two functions that I want to run when user selects option. I have tried with a conditional. It looks something like this, but the h2 doesn't render.

  function a() {
    return <h2>a</h2>;
  }

  function b() {
    return <h2>b</h2>;
  }

  handleChange(e) {
    if (e.target.value == "a") {
      a()
    }
    else if (e.target.value == "b") {
      b()
    }
  }

  return (
    <select onChange={handleChange()}>
      <option value="a">a</option>
      <option value="b">b</option>
    </select>
  )

CodePudding user response:

If you want to render h2 a /h2 or h2 b /h2 you have to store it in a variable and then use this variable in the return of your component.

I'd probably do something like this:

const [title, setTitle] = useState();

  handleChange(e) {
    setTitle(e.target.value)
  }

  return (
<>
    <h2>{title}</h2>
    <select onChange={handleChange}>
      <option value="a">a</option>
      <option value="b">b</option>
    </select>
</>
  )

CodePudding user response:

You can use a ternary operator to conditionally call the correct function based on the selected option. Here is an example:

function a() {
  return <h2>a</h2>;
}

function b() {
  return <h2>b</h2>;
}

function handleChange(e) {
  const selectedValue = e.target.value;
  const element = selectedValue === 'a' ? a() : b();
  
  // render the element somewhere in your component
}

return (
  <select onChange={handleChange}>
    <option value="a">a</option>
    <option value="b">b</option>
  </select>
)

Note that in the handleChange function, I used a ternary operator to determine which function to call based on the selected value. Then, I render the resulting element somewhere in the component.

  • Related