Search code examples
androidreactjsreact-nativetextinput

Change TextInput Style on Focus React Native


First of all, I've researched through other posts and find this How to change styling of TextInput placeholder in React Native?

The issue with the solutions in the post is once fontStyle is set to italic, it won't go back to normal font (I'm guessing that it can't be overridden unless the component updates). Here is my code sample

  <TextInput
    style={
      this.state.value.length === 0
      ? {fontStyle: 'italic', color: 'white'} // font changed to white and italic
      : {fontStyle: 'normal', color: 'black'} // font changed to black but stays italic
    }
    value={this.state.value}
  />

I came up with some hack by forcing the TextInput to update using forceUpdate() or set a key to the component, but this caused the keyboard UI to close when user is typing which is bad for UX.

I'd like to simply comment on the linked post instead but my reputation is not enough.

Is that intended behavior or did I make any mistake? If anyone can provide some explanation / solution, it will be greatly appreciated.

P.S. Tested on Android using the latest React Native


Solution

  • Use onFocus for the text input to handle your case. Because whenever you focus text input and start typing it will update the state and component will re-render. Look at this expo snack with the example usage.

    state = { isFocused: false }; 
    
    onFocusChange = () => {
        this.setState({ isFocused: true });
    }
    
    <TextInput 
        onFocus={this.onFocusChange}
        placeholder='Enter Input Here'
        style={(this.state.isFocused) ? {fontStyle: 'normal', color: 'black'} : {fontStyle: 'italic', color: 'white'}} 
     />
    

    so learn more about component lifecycle then you'll know how to handle more of these type of cases and also always read documentation before using a component then you'll easily find the solution for your specific case.