1

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() {
    // some logic
    return <h2>{result of some logic}</h2>;
  }

  function b() {
    // some logic
    return <h2>{result of some logic}</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>
  )
1
  • 2
    What are you expecting your returned JSX <h2> to do? (Right now, handleChange() doesn't use it, and it will just be discarded) Commented Dec 1, 2022 at 16:31

1 Answer 1

1

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>
</>
  )
Sign up to request clarification or add additional context in comments.

2 Comments

i realize now that i have written my example code badly. specifically the two functions. I'm not trying to return h2 a or h2 b. I'm returning something completely different, the function does some logic then gives a return in an h2.
@Scottsdaaale Maybe take a look at the parenthesis () you included in your onChange={handleChange()}. It's possible that is the bug in your code. Otherwise your code pretty much does what you expect it to. The above answers assume that you wished to show the return value to the user. If that was not the case, then you need to take that returned JSX (the h2 tag and actually do something with it inside the onChange function)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.