Ad

How To Clear TextInput On Send Button In React Native With Redux

I am working on chat app using react native with redux, where messages are sending through the send button. But whenever I sent a message on hitting the send button, the TextInput is not clearing. I want to clear the TextInput field on hitting the send button. Here I am working in redux so I don't want to use state with value.

Here is the code :

class Chat extends Component {

  componentWillMount() {
    this.props.fetchChat(this.props.receiverId);  
}

message(text) {
  this.props.writeMsg(text);    
}
onSend = () => {

  const { userId , receiverId, text } = this.props;
  this.props.sendMessage({userId , receiverId, text});
}

  render() {

    return (
      <View style={{ flex: 1 }}>

            <FlatList 
              inverted={-1}
              style={styles.list}
              extraData={this.props}
              data={this.props.convo}
              keyExtractor = {(item) => {
                return item.id;
              }}
              renderItem=   
              <ChatItem value={this.renderItem} />           
              />

             <MessageInput 
             onChangeText={text => this.message(text)}
             onPress={this.onSend }
            />          
      </View>
    );
  }
}

And this is the component MessageInput's code:

  <View style={inputContainer}>
            <TextInput style={inputs}
                placeholder="Write a message..."
                onChangeText={onChangeText}
              />
          </View>

            <TouchableOpacity style={btnSend} onPress={onPress }>
              <Icon
            name='send'
            type='MaterialIcons'
            color='#fff'
            style={iconSend}
            />  
            </TouchableOpacity>
Ad

Answer

You can use a ref to clear the value from Chat.

Add a new ref inside your constructor

constructor(props) {
  super(props);
  this.textInput = React.createRef();
}

Pass the ref into MessageInput.

render() {
  ...
  <MessageInput 
    onChangeText={text => this.message(text)}
    onPress={this.onSend }
    ref={this.textInput}
  />
  ...  
}

Modify MessageInput (I am going to assume it's a functional component)

const MessageInput = (props, ref) => (
  ...
  <TextInput style={inputs}
    placeholder="Write a message..."
    onChangeText={onChangeText}
    ref={ref}
  />
  ...
)

Finally, switch back to the Chat component and update onSend

onSend = () => {
  const { userId , receiverId, text } = this.props;
  this.props.sendMessage({userId , receiverId, text});
  this.textInput.current.clear(); // Clear the text input
}
Ad
source: stackoverflow.com
Ad