Here I want to assign the data from textInput to variable a. How can I do it?
(That is, when the user enters data in textInput, I want to assign it to variable a.)
import React, { Component } from 'react'
import { Text, View, TextInput} from 'react-native'
export default class deneme1 extends Component {
constructor(props) {
super(props);
this.state = {
a:"",
};
}
render() {
return (
<View>
<View style={styles.textinput}>
<TextInput
placeholderTextColor='white'
style={styles.textinputtext}
/>
</View>
</View>
)
}
}
You can try this one
<TextInput
placeholder={"A Variable"}
onChangeText={(text) => this.setState({a: text}) }
value={this.state.a}
/>
Related
I've got a react native form with a button that should autofill some of the field based on some user's information. The point is that even if I update the state variable related to a TextInput, the TextInput does not display such data. Here's a short snippet for the sake of simplicity
export default class Component extends React.Component {
constructor(props) {
super(props);
this.state = {
value: null
}
}
autocompile = () => {
this.setState({"value": "new value"})
}
render() {
return (
<View>
<TouchableOpacity
onPress={() => {
this.autocompile
}}>
<Text>Autocompile</Text>
</TouchableOpacity>
<TextInput
onChangeText={(value) => this.setState({'value': value})}
value={this.state.value}
/>
</View>
)
}
}
}
Following this example, if I clicked "Autocompile", the TextInput below wouldn't show the new value, even though the state variable would be updated. My question is, how can I update a TextInput displayed value from the external without typing in?
Class Component Solution
import React from 'react';
import { Text, View, TextInput, TouchableOpacity } from 'react-native';
export default class Component extends React.Component {
constructor(props) {
super(props);
this.state = { value: '' };
this.autocompile = this.autocompile.bind(this);
}
autocompile() {
this.setState({ value: 'new value' });
}
render() {
return (
<View>
<TouchableOpacity onPress={this.autocompile}>
<Text>Autocompile</Text>
</TouchableOpacity>
<TextInput
onChangeText={(value) => this.setState({ value: value })}
value={this.state.value}
/>
</View>
);
}
}
Function Component Solution
import React, { useState } from 'react';
import { View, TouchableOpacity, Text, TextInput } from 'react-native';
const App = () => {
const [value, setValue] = useState('');
const autocompile = () => setValue('new value');
return (
<View>
<TouchableOpacity onPress={() => autocompile()}>
<Text>Autocompile</Text>
</TouchableOpacity>
<TextInput onChangeText={(value) => setValue(value)} value={value} />
</View>
);
};
export default App;
You need to change this
autocompile = () => {
this.setState({"value": "new value"})
}
to
autocompile = () => {
this.setState({ value: 'new value' })
}
and this one also
onChangeText={(value) => this.setState({'value': value})}
to
onChangeText={(value) => this.setState({ value })}
Hello I have a problem with re rendering the component below you can see my code for the first screen within that I have a custom component:
class Ahelle extends React.Component{
constructor(props){
super(props)
this.state={
mamad:10
}
}
render(){
return (
<View style={{backgroundColor:"white"}}>
<ScrollView>
<CustomSlider defaultValue={0} />
<CustomSlider defaultValue={this.state.mamad} disabled={true}/>
<TouchableOpacity style={{width:100,height:100,alignSelf:"center"}} onPress={()=>{this.setState({mamad:20})}}><Text>dddd</Text></TouchableOpacity>
</ScrollView>
</View>
);
}
}
Here I have a custom component and I pass a default value for showing but when I change the state , it is not changing the value I passed as props.
here is my custom slider component and its state, props and any other details.
class Test extends React.Component{
constructor(props){
console.log(props)
super(props)
this.state = {
value: props.defaultValue
};
}
render(){
return(
<Slider
style={{width: wp("70%")}}
value={this.state.value}
/>
)
}
}
export default Test;
SEE THE PROBLEM IN ACTION
Thank you for your time
Your slider component never does anything with updated prop values that are passed. Coincidentally, it's also a react anti-pattern to store passed props in local component state. You can, and should, consume them directly. Just pass this.state.mamad to the value prop and consume. You can also pass along any additional props by spreading them in to the slider component.
class Test extends React.Component {
render() {
return (
<Slider
style={{ width: wp("70%") }}
value={this.props.value}
{...this.props}
/>
);
}
}
export default Test;
Usage
<CustomSlider value={this.state.mamad} disabled={true} />
If you really wanted to store the passed defaultValue prop and keep it updated, then implement the componentDidUpdate lifecycle function. Note, this is not the recommended solution.
class Test extends React.Component {
constructor(props) {
console.log(props);
super(props);
this.state = {
value: props.defaultValue
};
}
componentDidUpdate(prevProps) {
const { defaultValue } = this.props;
if (prevProps.defaultValue !== defaultValue) {
this.setState({ value: defaultValue});
}
}
render() {
return <Slider style={{ width: wp("70%") }} value={this.state.value} />;
}
}
export default Test;
Your code is correct. I tested it.
App.js
import React from "react";
import { Text, View, ScrollView, TouchableOpacity } from "react-native";
import CustomSlider from "./CustomSlider";
export default class Ahelle extends React.Component {
constructor(props) {
super(props);
this.state = {
mamad: 10,
};
}
render() {
return (
<View style={{ backgroundColor: "white" }}>
<ScrollView>
<CustomSlider defaultValue={0} />
<CustomSlider defaultValue={this.state.mamad} disabled={true} />
<TouchableOpacity
style={{ width: 100, height: 100, alignSelf: "center" }}
onPress={() => {
this.setState({ mamad: 20 });
}}
>
<Text>dddd</Text>
</TouchableOpacity>
</ScrollView>
</View>
);
}
}
CustomSlider.js
import React from "react";
import { Text } from "react-native";
export default class CustomSlider extends React.Component {
render() {
return <Text>defaultValue: {this.props.defaultValue}</Text>;
}
}
Result:
View Result
I have a component and import it in specific screen, in this screen i have a button when clicks i open modal contain component it's a "recorder" so after i record voices i want to take this voice and save them into Parent screen as a state or something!
in the recorder component, I save voices data into state! but how can i pass it to other parent screens!?
so how can I handle it?
here is shots
Parent Screen "after click add voice I show the modal"
Parent Screen
Here's a modal contain a recorder component
Modal
CODE
Component
" I pass data to PassDataToModal state inside componentDidMount "
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, TouchableOpacity, View} from 'react-native';
import {AudioRecorder, AudioUtils} from 'react-native-audio';
import Sound from 'react-native-sound';
import Icon from 'react-native-vector-icons/MaterialIcons';
class RecorderScreen extends Component {
state = {
PassDataToModal: null,
};
componentDidMount() {
AudioRecorder.requestAuthorization().then(isAuthorised => {
this.setState({hasPermission: isAuthorised});
AudioRecorder.onFinished = data => {
console.log('data', JSON.stringify(data));
this.setState({PassDataToModal: data});
};
});
}
render() {
return (
<View style={styles.container}>
<View style={styles.controls}>
{this._renderPlayButton(() => {
this._play();
})}
{this._renderRecordButton(this.state.recording)}
{this._renderStopButton('Stop', () => {
this._stop().then(() => this.setState({currentTime: 0}));
})}
</View>
<Text style={styles.progressText}>{this.state.currentTime}s</Text>
</View>
);
}
}
export default RecorderScreen;
Parent Screen
import Modal from 'react-native-modal';
import RecorderScreen from './Recorder';
class Order extends Component {
constructor(props) {
super(props);
this.state = {
isModalVisible: false,
};
}
toggleModal = () => {
this.setState({isModalVisible: !this.state.isModalVisible});
};
render() {
return (
<View style={styles.container}>
<TouchableOpacity
onPress={this.toggleModal}
>
<Icon name="mic" color="#333" size={20} />
<Text style={{paddingHorizontal: 5}}>Add Voice</Text>
</TouchableOpacity>
<Modal
style={{margin: 0}}
isVisible={this.state.isModalVisible}
>
<View>
<TouchableOpacity onPress={this.toggleModal}>
<Icon name="close" color="#000" size={25} />
</TouchableOpacity>
<RecorderScreen /> // Component
</View>
</View>
)
}
}
In your parent component pass a function to your RecorderScreen component that will send the necessary data up. Docs on lifting state up.
So in your parent you'd have something like:
setData = (data) => {
// Set this to whatever you need it to be named
this.setState({childData: data});
}
Then pass the function as a prop:
<RecorderScreen setData={this.setData} />
And finally, call it in the child however needed (If I'm following the code something like this):
componentDidMount() {
AudioRecorder.requestAuthorization().then(isAuthorised => {
this.setState({hasPermission: isAuthorised});
AudioRecorder.onFinished = data => {
this.props.setData(data);
};
});
}
Then your parent component will have access to the child's data that you have lifted up.
FlatList Component working complete if i click Android it show in Android in aler but i have to pass that bind value into Subscribe component instead of alert.
should i have to pass data into state and for use it as a props in other component ?
import React, { Component } from 'react';
import { AppRegistry, FlatList, StyleSheet, Text, View,Alert } from 'react-native';
export default class FlatList extends Component {
constructor(props) {
super(props);
this.updateKey = this.updateKey.bind(this);
this.state = {};
}
updateKey(keyData) {
this.setState({ keyData: keyData });
}
getListViewItem = (item) => {
Alert.alert(item.key);
}
render() {
return (
<View style={styles.container}>
<FlatList
data={[
{key: 'Android'},{key: 'iOS'}, {key: 'Java'},{key: 'Swift'},
{key: 'Php'},{key: 'Hadoop'},{key: 'Sap'},
]}
renderItem={({item}) =>
<Text style={styles.item}
onPress={this.getListViewItem.bind(this, item)}>{item.key}</Text>}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
item: {
padding: 10,
fontSize: 18,
height: 44,
},
})
AppRegistry.registerComponent('flatList', () => FlatList);
import React, { Component } from 'react'
import { View, Item } from 'react-native';
export default class Subscribe extends Component {
render() {
return (
<View>
<Text>{item.key}</Text>
</View>
)
}
}
Yes, if you want to pass it as prop to a child component you can set it inside your state and pass it to the child component you are talking about.
To accomplish this you just have to change your Alert to: this.setState( { selectedValue: item } )
Then your child would look something like:
<Child item = {this.state.selectedValue} />
And you will be able to access it in your child simply doing:
this.props.item
I'm new to react native. I am trying to get a 'Key' from a different component. I mean I am trying to call a function from a different component, as a parent component. But, I'm totally jumbled with all these reference calls and all. Please suggest to me how to call a function from a different component.
// AddScreen.js
import React, { Component } from 'react';
import { AppRegistry, AsyncStorage, View, Text, Button, TextInput, StyleSheet, Image, TouchableHighlight, Linking } from 'react-native';
import styles from '../components/styles';
import { createStackNavigator } from 'react-navigation';
import History from '../components/History';
export default class AddScreen extends Component {
constructor(props) {
super(props);
this.state = {
myKey: '',
}
}
getKey = async () => {
try {
const value = await AsyncStorage.getItem('#MySuperStore:key');
this.setState({ myKey: value });
} catch (error) {
console.log("Error retrieving data" + error);
}
}
async saveKey(value) {
try {
await AsyncStorage.setItem('#MySuperStore:key', value);
} catch (error) {
console.log("Error saving data" + error);
}
}
componentDidMount() {
this.getKey();
}
render() {
const { navigate } = this.props.navigation;
return (
<View style={styles.MainContainer}>
<View style={styles.Date_input}>
<TextInput
placeholder="Add input"
value={this.state.myKey}
onChangeText={(value) => this.saveKey(value)}
/>
</View>
<View style={styles.getKeytext}>
<Text >
Stored key is = {this.state.myKey}
</Text>
</View>
<View style={styles.Historybutton}>
<Button
onPress={() => navigate('History')}
title="Press Me"
/>
</View>
</View>
)
}
}
//History.js
import React, { Component } from 'react';
import AddScreen from '../components/AddScreen';
import {
AppRegistry,
StyleSheet,
Text,
TextInput,
Button,
View,
AsyncStorage
} from 'react-native';
export default class History extends Component {
constructor(props) {
super(props);
this.state = {
myKey: ''
}
}
render() {call async function synchronously
return (
<View style={styles.container}>
<Button
style={styles.formButton}
onPress={this.onClick}
title="Get Key"
color="#2196f3"
accessibilityLabel="Get Key"
/>
<Text >
Stored key is = {this.state.mykey}
</Text>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
padding: 30,
flex: 1,
backgroundColor: '#F5FCFF',
},
});
I just want to call the getKey function from the History component to get the myKey value on the History component's screen.
Please suggest to me, by taking my components as an example.
You just simply need to pass the key via navigation parameters.
<Button
onPress={() => navigate('History', { key: this.state.myKey })}
title="Press Me"
/>
and in your history component you can do
render() {
const key = this.props.navigation.getParam('key');
return (
// other code
)
}
You can read more about passing parameters here. https://reactnavigation.org/docs/en/params.html