I want to make a simple textinput operation. User can input its name.
I created class based parent (App.js) and functional based (InputName.js)
I called child component in parent class as
<InputName />
I created InputName.js as
const InputName = () => {
const [text, setText] = React.useState(null);
return ( <TextInput
autoCapitalize='none'
onChangeText={(text) => setText(text)}
style={styles.userTextInput} />)
}
My question is How can I reach onChangeText value in child component from parent.
//imports
import EmailInput from '../components/EmailInput';
class Login extends Component {
state = {
inputValue: '',
}
constructor(props) {
super(props);
}
onChangeText = (text) => {
this.setState({inputValue: text.target.value});
};
render() {
return (
<EmailInput value={this.state.inputValue} onChangeText={(text) => this.onChangeText(text)} /> )}};
// Input File
const EmailInput = (onChangeText, value) => {
const [text, setText] = React.useState(null);
return ( <TextInput
autoCapitalize='none'
value={value}
onChangeText={onChangeText}
style={//styles} />)
}
just pass your method from child component in parent class. here is an working example:
import React from 'react';
import {TextInput} from 'react-native';
class EmailInput extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
const {onTextChange, inputValue} = this.props;
return (
<TextInput
autoCapitalize="none"
value={inputValue}
onChangeText={onTextChange}
/>
);
}
}
export default EmailInput;
in your main class just do the following:
import React from 'react';
import {
SafeAreaView,
} from 'react-native';
import EmailInput from '../components/EmailInput';
class LandingScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
locals: {},
inputValue: '',
};
}
onTextChange = text => {
this.setState({inputValue: text.target.value});
};
render() {
return (
<SafeAreaView style={styles.container}>
<EmailInput
inputValue={this.state.inputValue}
onChangeText={text => this.onTextChange(text)}
/>
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
});
const mapStateToProps = state => {
const apiLoading = state.common.apiLoading;
return {
apiLoading,
};
};
export default connect(mapStateToProps, actions)(LandingScreen);