Yesterday I started learning React Native. Unfortunately I encounter some difficulties right at the beggining. I was trying to write simple list, which contains some input, and when user clicks "Add new" button, list will extend with new item. When I am trying to use this.state.newName variable in a new list element React is throwing me exception:
" Invariant Violation: Objects are not valid as a React child (found: object with keys {dispatchConfig, _targetInst, isDefaultPrevented, isPropagationStopped, _dispatchListeners, _dispatchInstances, type, target, currentTarget, eventPhase, bubbles, cancelable, timeStamp, defaultPrevented, isTrusted, nativeEvent}). If you meant to render a collection of children, use an array instead."
My code is really simple:
export default class HelloWorldApp extends Component {
constructor() {
super();
this.state = {
newName: "",
peopleList: [
{ key: "1", name: "Jonathan", lastname: "Smith" },
{ key: "2", name: "Tomasz", lastname: "Kowalski" },
{ key: "2", name: "Adrian", lastname: "Jakubowski" },
]
}
}
addNew() {
let newName = this.state.newName;
this.setState({
peopleList: [...this.state.peopleList, {key: newName, name: newName, lastname: "Added"}]
});
}
render() {
return (
<View style={styles.peopleList}>
<Text>People I know:</Text>
<TextInput
value={this.state.newName}
onChange={(text) => this.setState({newName: text})}
/>
<Button title="Add new!"
onPress={() => this.addNew()}
/>
<FlatList
data={this.state.peopleList}
renderItem={({ item }) => <Text style={styles.item}>Imie: {item.name} Nazwisko: {item.lastname}</Text>} />
</View>
);
}
}
When I am not using this.state.newName, and just pass some string like:
let newName = "Adam";
It will works just fine. What can be a cause?
onChange={(text) => this.setState({newName: text})}
should be:onChangeText={(newName) => this.setState({ newName })}
– Samuli Hakoniemi