Home > front end >  Changing borderWidth dynmically in react native does not work
Changing borderWidth dynmically in react native does not work

Time:03-08

This is my code:

const [focus1, setFocus1] = useState(false);
<TextInput
style={{
    ...styles.input_container,
    borderColor: `${focus1 ? colors.darkPurple : "#b8b8b850"}`,
    borderWidth: `${focus1 ? 3 : 1}`,
}}
placeholder="Enter Username"
placeholderTextColor={colors.lightGray}
onFocus={() => setFocus1(true)}
onBlur={() => setFocus1(false)}
/>

The app crashes when the screen is loaded. How to change the borderWidht dynamically?

CodePudding user response:

The crash could be happening because you're giving the styles wrong. The backticks in the style are resulting in the specified values to be quoted twice. Border color would be resolved to this`

`"#b8b8b850"'

whereas it should be only quoted once. And borderwidth would be resolved into

`3`

whereas the value is supposed to be an integer and not a string.

Try it like this.

<TextInput
style={[
  styles.input_container,
  borderColor: focus1 ? colors.darkPurple : "#b8b8b850",
  borderWidth: focus1 ? 3 : 1,
]}
placeholder="Enter Username"
placeholderTextColor={colors.lightGray}
onFocus={() => setFocus1(true)}
onBlur={() => setFocus1(false)}
/>

CodePudding user response:

borderWidth is supposed to be a number, see https://reactnative.dev/docs/view-style-props#borderwidth

So you should write borderWidth: focus1 ? 3 : 1

  • Related