0

I need to keep input text in TextInput while the Modal is opened. FYI, TextInput is not a child component of Modal

I know it doesn't normal but the situation is pushing me to do this.

Please help me if you have experience in solving this kind of problem.

Smart Solutions
  • 869
  • 2
  • 10
  • 30

2 Answers2

0

Use can use Ref object to focus the text input every time modal will be visible

check this code,,,,


export default function App() {
  const [visible, setVisible] = React.useState(false);

  const input = React.createRef();
  React.useEffect(() => {
    if (visible) {
      input.current.focus();
    }
  }, [visible]);
  return (
    <View style={styles.container}>
      <Button
        title="Click"
        onPress={() => {
          setVisible(true);
        }}
      />
      <Modal
        visible={visible}
        onRequestClose={() => {
          setVisible(false);
        }}>
        <View style={styles.modal}>
          <TextInput ref={input} />
        </View>
      </Modal>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  modal: {
    width: '100%',
    height: '100%',
  },
});
Ashwith Saldanha
  • 1,700
  • 1
  • 5
  • 15
0

Use this way

CustomModal.js

const CustomModal = React.forwardRef((props, ref) => (
  React.useEffect(() => {
   ref.current.focus();
 }, []);

  return (
    <Modal isActive={props.isActive}>
      <ModalClose onClick={props.handleClose} />
    </Modal>
  )
))

App.js

export default function App() {
  const [visible, setVisible] = React.useState(false);

  const input = React.createRef();
 
  return (
    <View >
      <TextInput ref={input} /> // Create textinput outside here
      <Button
        title="Click"
        onPress={() => {
          setVisible(true);
        }}
      />
      <CustomModal    
    isActive={visible} 
    handleClose={()=>{}} 
    ref={input}
      /> 
    </View>
  );
}
Nooruddin Lakhani
  • 7,507
  • 2
  • 19
  • 39