0

I'm new ot react native and am having a hard time with the idea of not using inheritance, but rather composition.

My scenario: I'm creating a component (focusedTextInput) which shows one InputText. My component simply adds functionality to change the style of the TextInput on focus.

I'm using FocusedTextInput in another component which contains five focusedTextInput and I configure those to only have one character at a time and to auto-skip to the next FocusedTextInput when the character is entered (using the focus() method).

Where I'm running into issues is the my FocusedTextInput does not have a focus method (and I don't want to expose the TextInput).

So do I need to surface all the method that might be used from TextInput on FocusedTextInput or is there a better way?

otusweb
  • 1,638
  • 1
  • 19
  • 30
  • so instead of calling the focus method on the input, you can pass a prop to determine whether it should be focused or not like `` then you just need to keep that state information in a common ancestor between your input and wherever else wants to interact with it – azium Jan 29 '18 at 22:44
  • There's a page in the documentation about this https://reactjs.org/docs/lifting-state-up.html – azium Jan 29 '18 at 22:44

1 Answers1

0

See this answer React set focus on input after render on stack overflow.

I think this applies to react-native but it does work in the web.

That shows you how to set a ref to a component. And in the CDM set the focus to that component.

To extend how that works so you can set the focus to a specific input (if there are many) is to add a prop called setFocused

Change the CDM to

 // Set the focus on first render.    
componentDidMount(){
    if (this.props.setFocus) {
       this.nameInput.focus();
    }
}

// focus if the prop changes
componentWillRecieveProps(nextProps) {
    if (this.nextProps.setFocus) {
       this.nameInput.focus();
    }
}
bluesixty
  • 2,367
  • 3
  • 21
  • 21