I keep getting the error undefined is not an object (evaluating 'event.preventDefault)
Clearly I am not allowed to give an event parameter on this.handleChange on my child component that is rendered in the parent component.
Why I don't know. Been following a few online examples and they all did quite the same thing so I don't know why it's impossible to use (event) in my handleChange function.
// Parent component //
export class Home extends Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
state = {
name: ""
};
handleChange = event => { // so this event causes problems ...
// when I skip event I get my console.log
// and don't receive any errors
event.preventDefault();
console.log("handleChange has fired");
this.setState({
name: event.target.value
});
console.log(this.state.name);
};
render() {
console.log(this.state.name);
return (
<View style={styles.container}>
<MainTitle message={"Bienvenue " + this.state.name} />
<InputField getNewName={this.handleChange} />
<PrimaryButton text={"button"} />
</View>
);
}
}
// Child component //
class InputField extends Component {
constructor(props) {
super(props);
}
render() {
const { getNewName } = this.props
return (
<TextInput
placeholder={"Please enter your name"}
onChangeText={() => getNewName()}
/>
);
}
}
export default InputField;
I am assuming you don't need the native event
object in your TextInput, because you want to use onChangeText which is perfect for your use case and easier to use. But you should pass the new value to your this.props.getNewName like this:
<TextInput
style={{height: 40, borderColor: 'gray', borderWidth: 1}}
onChangeText={(newText) => this.props.getNewName(newText)}
value={....}
/>
see here: https://facebook.github.io/react-native/docs/textinput And your handler should not expect the event, but the newText passed from child TextInput:
handleChange = newTextHere => {
console.log("handleChange has fired", newTextHere);
this.setState({
name: newTextHere
});
console.log(this.state.name);
};