I’m trying to append elements to my in react native, using this.state.
But it doesn’t return the Text element. My View stays empty…can anyone help?
I’m using this as a reference.
function App() {
const {register, setValue, handleSubmit} = useForm();
this.state = {message: []};
useEffect(() => {
register('author');
register('message');
}, [register]);
var socket = io.connect('http://localhost:3000/');
const onSubmit = data => {
renderMessage(data);
socket.emit('sendMessage', data);
};
socket.on('receivedMessage', function (data) {
renderMessage(data);
});
const renderMessage = data => {
this.state.message.push(data);
};
return (
<View style={styles.sectionContainer}>
<TextInput
style={styles.sectionAuthor}
placeholder="author"
onChangeText={text => setValue('author', text)}
/>
<View style={styles.sectionDescription}>
{this.state.message.map(item => (
<Text>{item.author}</Text>
))}
</View>
<TextInput
style={styles.sectionMessage}
placeholder="Message"
onChangeText={text => setValue('message', text)}
/>
<Button onPress={handleSubmit(onSubmit)} title="Enviar" />
</View>
);
}
2
Answers
You are mixing functional component and class component.
You should use useState to manage state instead of
this.state
then in your rendering, it should use
messages
.