Home > Software engineering >  React Native setState will render JSX Element
React Native setState will render JSX Element

Time:05-12

I have two text input and one button

when I click the button, it will change its color

like

enter image description here

My question is when I click the button (setState)

only JSX-Element will render and TextInput will be cleared

(input)

enter image description here

(click)

enter image description here

How can I use JSX-TextInput and avoid this situation

code-example https://snack.expo.dev/@tsaihenry/add958

CodePudding user response:

You can use controlled input field. Controlled component will behave as per as your state. It will clear input fields whenever you will press the button.

const [textValue, setTextValue] = useState("");


  const pressAgree = () => {
    setAgree(!agree);
    setTextValue("");
  }

 <TextInput
        value={textValue}
        style={styles.input}
        placeholder="useless placeholder"
      />

       <Button
        title="Press me"
        onPress={pressAgree}
        color = { (agree) ? "#f194ff" : "#94fff1"}
      />

CodePudding user response:

As per your code TextElement is a function which returns a JSX.Element. So change <TextElement /> to {TextElement()} which will render the JSX element returned by the function. With that the input won't be cleared.

return (
    <View style={styles.container}>

       <TextInput
        style={styles.input}
        placeholder="useless placeholder"
      />

      {TextElement()}
      
      <Button
        title="Press me"
        onPress={pressAgree}
        color = { (agree) ? "#f194ff" : "#94fff1"}
      />

    </View>
  );
  • Related