Get value from a TextInput component in react native - javascript

Dynamically generate a TextInput when you press a button but I can’t get the value that the user digits,try to use states but I can’t because it’s not with the other general textInputs but it’s imported as Field.
try to create a state in the component file and move it to the general view and print it to see if it works and not...is there any way to bring this state?
general view:
import Campo from './campoInput';
constructor(props){
super(props);
this.state={
Cbusto:"",
Ccintura:"",
Ccadera:"",
valueArray: []
};
this.addNewEle = false;
}
agregarCampo=()=>{
this.addNewEle = true;
const newlyAddedValue = { text: 'prueba'};
this.setState({
valueArray: [...this.state.valueArray, newlyAddedValue]
});
}
render(){
return(
------Here are the normal textInput-----
<View style={{ flex: 1, padding: 4 }}>
{this.state.valueArray.map((ele) => {
return <Campo item={ele} />;
})}
</View>
<View style={styles.flex}>
<View style={styles.ButtonAdd}>
<Button
title="Add input"
color="#B13682"
onPress={this.agregarCampo}
></Button>
</View>
)
}
Component:
constructor(props){
super(props);
this.state={
info:""
};
}
render(){
return(
<View>
<Text>pruba:{this.props.item.text}</Text>
<View style={styles.input}>
<TextInput onChangeText={(text) => this.setState({info:text})}></TextInput>
</View>
</View>
)
}

can be solved by adding the onChangeText event to the Field component in the overview and in the same way in the TextInput of the component being imported, using props status
General view:
<View style={{ flex: 1, padding: 4 }}>
{this.state.valueArray.map((ele) => {
return <Campo item={ele}
onChangeText={(text) => this.setState({ info: text })}
/>;
})}
</View>
Component
<View>
<Text>pruba:{this.props.item.text}</Text>
<View style={styles.input}>
<TextInput onChangeText={this.props.onChangeText}></TextInput>
</View>
</View>

Related

React native js. nothing shows when pressing the start button

I am trying to show or print the duration (timer) when the button start is pressed, but nothing is showing after pressing start. I tried doing Button instead of TouchableOpacity, but still, nothing changed.
class Timer extends Component {
constructor(props){
super(props)
this.state = {
count: 0
}
}
render () {
const {count} = this.state
return (
<ScrollView>
<SafeAreaView style={styles.container}>
<View style={styles.textInputContainer}>
<Text style={styles.txtHello}>Press start when ready</Text>
<View style={styles.sep}>
</View>
<TouchableOpacity style={styles.button}
onPress={ () =>
<View style={styles.textInputContainer}>
<Text>
<h2> Duration: {count}</h2>
</Text>
</View>
}
>
<Text>start</Text>
</TouchableOpacity>
</View>
</SafeAreaView>
</ScrollView>
)
}
componentDidMount(){
this.myInterval = setInterval(()=>{
this.setState({
count: this.state.count + 1
})
}, 1000)
}
}
I don't think this is a right way to do it in React. What you would like to do is set a isVisible state, change it with your onPress props in Button/TouchableOpacity and finally conditionally show the view you want to display based on that isVisible variable. Something like this:
class Timer extends Component {
constructor(props){
super(props)
this.state = {
isVisisble:false;
}
}
render(){
return(
<View>
<TouchableOpacity
onPress={ () => this.setState((prevState)=>{isVisible:!prevState.isVisible})}
>
<Text>start</Text>
</TouchableOpacity>
{this.state.isVisible && <View></View>} <- Conditional View here
</View>
)}

Update page data

I need your help. I have a problem with updating data on a page. Basically I have a homepage where there is data like "FirstName: ...", "LastName: ..." which are retrieved from the login.
Once the login has been completed, you will automatically be taken to the Homepage page each time the app is started.
In this way I retrieve the information on the Homepage page.
The problem is that the user can modify this data through a form (ModifyProfile), and once the data is done they are not updated.
How can I update them anyway?
Thank you.
Homepage.js
class HomepageUtente extends Component {
constructor(props) {
super(props);
this.state = {
}
}
render() {
const FirstName = global.utente.data.Person.FirstName;
const LastName = global.utente.data.Person.LastName;
return (
<View style={style.container}>
<View style={style.page}>
<Icon name="user-circle" color="#64c7c0" size={70} onPress={() => Actions.yourprofile({ cf: Username } )} />
<Text
style={{ textAlign: 'center', fontSize: 20, }}>{"Welcome"}
</Text>
<Text style={{ textAlign: 'center', fontSize: 20, color: '#64c7c0', fontWeight: 'bold' }}>
{FirstName} {LastName}
</Text>
<Text style={{ color: '#64c7c0', paddingTop: 20 }} onPress={() => Actions.ModifyProfile({ cf: Username })} >Modify Profile</Text>}
</View>
</View>
)
}
}
ModifyProfile
export default class ModificaProfilo extends Component {
constructor(props) {
super(props);
this.state = {};
}
findUtente(cf) {
//Search data cf in the db
//......
//......
.then(response => {
let utente = response.docs[0];
console.log("Utente: " + utente)
console.log("Sei qui 1")
utente.Person.FirstName = this.state.FirstName;
utente.Person.LastName = this.state.LastName;
global.utente.db.localdb().put(utente);
})
.catch(function(err) {
console.log(JSON.stringify(err));
})
}
render() {
return (
<View style={style.container}>
<View style={style.page}>
<KeyboardAwareScrollView>
<View style={style.inputContainer}>
<TextInput
style={style.inputs}
placeholder="Name"
placeholderTextColor="#64c7c0"
keyboardType="default"
underlineColorAndroid="grey"
onChangeText={FirstName =>
this.setState({ FirstName })
}
/>
</View>
<View style={style.inputContainer}>
<TextInput
style={style.inputs}
placeholder="Surname"
placeholderTextColor="#64c7c0"
keyboardType="default"
underlineColorAndroid="grey"
onChangeText={LastName =>
this.setState({ LastName })}
/>
</View>
<View style={style.footer}>
<TouchableOpacity
style={[style.button, style.buttonOK]}
onPress={() => this.findUtente(this.props.cf)}
>
<Text style={style.buttonTesto}>Modifica</Text>
</TouchableOpacity>
</View>
Actually, you can do that but you shouldn't. Let's solve it first.
The component in Homepage.js, we call it A ;
The component in ModifyProfile, we call it B ;
You need a reference to component A, and then call A.forceUpdate().
It means you add global.A = this in Homepage.js;
add global.A.forceUpdate() in ModifyProfile after you get the new data;
Why: React Component would reRender only if the state or props of the component changes, that's why you need to call forceUpdate to make component A reRender again unconditionally.
if your change the FirstName by global.utente.data.Person.FirstName = 'NewName', component A can not detect the change event.
By the way, you should use a state container like redux to help you, rather than a global variable. You can connect FirstName as your props.
I recommend dvajs which is easy to learn, you can just focus on the data and flow, you don't need to care about if a component should update most of the times.
And there is a starter of dvajs, you can just run it quickly followed by:
react-native-dva-starter
Forget it if I misunderstood your question.

React-Native: Access TextField value in another class

As an iOS dev I'm struggling a bit with react native.
I have two components inside different classes:
Component A is a view with a TextInput
class A extends Component<Props>{
state = {
textFieldValue: ""
};
render() {
return (
<View>
<TextInput placeholder={this.props.placeholderText}
ref={textField => {
this.textField = textField;
}}
value={this.state.textFieldValue}
onChange={e => this.setState({ textFieldValue: e.target.value})}/>
</View>
);}
}
Component B uses A in it's view
class B extends Component<Props>{
render() {
return (
<View>
<A placeholder={"test"}/>
<TouchableOpacity onPress={() => {
//show text of input A here
}}>
<View>
<Text>{text}</Text>
</View>
</TouchableOpacity>
</View>
);}
}
How can I access the value/state with the value of the TextInput in A from B to show it on the button press?
Try this on Class B
class B extends Component<Props>{
render() {
return (
<View>
<A placeholder={"test"} ref={c => this.textRef = c}/>
<TouchableOpacity onPress={() => {
//show text of input A here
alert(this.textRef.state.textFieldValue)
}}>
<View>
<Text>{text}</Text>
</View>
</TouchableOpacity>
</View>
);}
}
Access reference of class A through ref props, then get its own state.

How to use Checkbox in Dynamic List React Native?

I'm using react native List to generate a Dynamic list using a custom data array and in the ListItem. I am using nested checkbox in every list item and I can't set the switch. I tried it by setting array of state but it doesn't seem to work.
This is my list
const DashboardList = props => (
<List
style={props.ListStyle}
dataArray={props.ListData}
renderRow={item => <ListContent ListData={item} />}
/>
);
This is my listItem
class ListContent extends Component {
static navigationOptions = {
title: "ListContent",
header: null
};
constructor(props) {
super(props);
this.state = {
IsContentVisible: false
};
}
render() {
return (<ListItem>
<View>
<View>
<Left>
<View>
<CheckBox
checked={this.state.checked}
onPress={checked => {
this.setState({ checked: !this.state.checked });
this.props.CheckBoxChange(this.props.ListItem,
checked);}}/>
</View>
<View>
<Image
source={this.props.ListItem.DataFolderContent[0].Image}
resizeMethod="auto"
resizeMode="contain"
/>
</View>
<View>
<Text>
{this.props.ListItem.Name}
</Text>
</View>
</Left>
<Body>
<View>
<Badge style={{ backgroundColor: "#eeae30" }}>
<Text>{this.props.ListItem.DataFolderContent.length}
</Text>
</Badge>
</View>
</Body>
<Right >
<Switch
onTintColor="#eeae30"
value={this.state.switched}
onValueChange={() => {
this.setState({ switched: !this.state.switched });
this.props.SwitchToggled(this.props.ListItem);
}}
/>
</Right>
</View>
</View>
</ListItem>;
}
}

Render on TextInput Submit - React Native

In a a react native app I have some text and then a textinput rendered on the screen. I'm trying to figure out how to output the same text and the same textinput when I submit on in the original text field. I was thinking to do this recursively but I'm not sure how where and how implement the function to do so.
If it's in the same screen, than you can use local state. here's the example
class TestScreen extends Component {
constructor(props) {
super(props)
this. state = {
firstInput:'First Input',
secondInput:''
}
this.submit = this.submit.bind(this)
}
submit(){
this.setState({ secondInput: this.state.firstInput })
}
render() {
return (
<View style={{flex:1,marginTop:40}}>
<View>
<Text>Text Input #1</Text>
<TextInput
style={{height: 40, borderColor: 'gray', borderWidth: 1}}
onChangeText={(text)=> this.setState({firstText:text})}
value={this.state.firstInput}
/>
<Button
onPress={this.submit}
title="Submit"
/>
</View>
<View style={{marginTop:20}}>
<Text>Text Input #1</Text>
<TextInput
style={{height: 40, borderColor: 'gray', borderWidth: 1}}
value={this.state.secondInput}
/>
</View>
</View>
);
}
}
I hope that help. Thanks
Perhap you can use ref,state,conditional rendering. let's code talk
const MyInputs = (props) => {
inputs =props.inputs
result=inputs.map(function(value,index){
return(
<TextInput key={index} style={styles.input} value={value} />
)
})
return(
<View>
{result}
</View>
)
}
class TestScreen extends Component {
constructor(props) {
super(props)
this. state = {
inputs:[]
}
this.submit = this.submit.bind(this)
this.clearText = this.clearText.bind(this)
}
submit(){
let lastInput=this._textInput._lastNativeText
let inputs=this.state.inputs
this._textInput.setNativeProps({text: ''});
inputs.push(lastInput)
this.setState({
inputs:inputs
})
}
clearText = () => {
this.setState({
inputCount: this.state.inputCount + 1,
})
this._textInput.setNativeProps({text: ''});
}
render() {
return (
<View style={{flex:1,marginTop:40}}>
<View>
<Text>Text Input #1</Text>
<TextInput
style={styles.input}
ref={component => this._textInput = component}
/>
<Button onPress={this.submit} title="Submit"
/>
</View>
<MyInputs inputs={this.state.inputs}/>
</View>
);
}
}

Categories