How to use useRef correctly with React in ionic5?

Asked

Viewed 61 times

0

I’m using the following dependencies:

Ionic/React: 5.0.7 React: 16.13.0 typescript: 3.8.3

I own a select:

<IonSelectOption ref={refExemplo} {..propsDeExemplo }>{textoDeExemplo}</IonSelectOption>

And whenever I click any button I want to clear the selected text, but without losing the state. Usually only with React (in javascript) just assign a ref to select and dps clean it so:

refExemplo.value = null;

But with Ionic I can’t assign any value.

To capture the desired text I do: frenteRef.current?.textContent

But when I try to clean the selected option as follows: frenteRef.current?.textContent = ""

i get:

The left-hand side of an assignment Expression may not be an optional Property access.

Any way to assign/clear the text of this select ?

  • if you are using a state for that component it should be changed? has the full code?

  • What state ? I would like to clear the selected option when clicking the button without changing the options, which in my case are stored in a state

  • 1

    But the state is for that very, now clean became strange ... by reference is not ideal ...

  • Eh, since I was using the state in number, when I set it as 0 it loses the reference as I wanted, it was simpler than I expected, put an answer on that for me to score =)

  • You can explain the problem yourself and mark it as a response

1 answer

0


As @Virgilio commented, using the ref for this case is not ideal. I solved the problem by resetting the state responsible for storing the select value. This worked because the possible values are in the IonSelectOption then when the value is reset, the selected option is reset.

In a text input I think the workaround should be a little different.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.