I'm new to react native I'm working on AutoCompleteTextView . I have one json file I need to display the country name in autocomplete view . I have display the country names of all countries. But while selecting the country it's not selecting. The json file which i'm displaying is.
My code for autocomplete is.
render() {
const { query } = this.state;
return (
<KeyboardAwareScrollView
innerRef={ref => this.scrollView = ref} //... Access the ref for any other functions here
contentContainerStyle={{flex: 1}}>
<View>
<View style={styles.autocompleteContainer}>
<Autocomplete
data={timezones}
defaultValue={query}
autoCapitalize="none"
autoCorrect={false}
onChangeText={text => this.setState({ query: text })}
placeholder="Enter Country"
renderItem={({ name, latlng }) => {
const prodNames = latlng.map(item => item.prodNames);
<TouchableOpacity onPress={() => this.setState({ query: text })}>
<Text>{name} {prodNames}</Text >
</TouchableOpacity>
}}
/>
</View>
<View>
<Text>Some content</Text>
</View>
Are you getting an error?
Try replacing this:
<TouchableOpacity onPress={() => this.setState({ query: text })}>
By this:
<TouchableOpacity onPress={() => this.setState({ query: name+''+prodNames })}>
Related
I have a modal with a React-Hook-Form that send data to my API and saves it in a MySql database, but when i click on the button, only 4 columns are filled('id', createdAt, updatedAt and user_id), and I have more 3 columns('title', 'description', 'photo').
export default function FeedModal() {
const [form, setForm] = useState([]);
const { register, handleSubmit, setValue } = useForm();
const [isModalVisible, setModalVisible] = useState(false);
useEffect(() => {
register({ title: 'title' });
register({ description: 'description' })
}, [register]);
const onSubmit = async ({ title, description, photo }) => {
const data = { title, description, photo };
await api.post('/posts/1/create')
.then(response => setForm(response(data)))
.then(JSON.stringify(form))
.catch(console.error());
return () => handleSubmit(onSubmit);
}
const toogleModal = () => {
setModalVisible(!isModalVisible);
}
My form:
<View style={styles.Card}>
<View style={styles.pubCard}>
<Text style={styles.intro}>Criar publicação</Text>
<TextInput
value={form.title}
name={'title'}
ref={register({ required: true })}
onChangeText={text => setValue("title", text, { shouldValidate: true })}
multiline={true}
style={styles.titleInput}
placeholder="Titulo">
</TextInput>
</View>
<View style={styles.btnView}>
<TouchableOpacity style={styles.upload} title="Selecionar Foto" >
<Text style={{ color: 'white', fontFamily: 'Montserrat_400Regular', textAlign: 'center' }}>Selecionar Foto</Text>
</TouchableOpacity>
</View>
<KeyboardAvoidingView style={styles.descView}>
<TextInput
value={form.description}
name={"description"}
ref={register({ required: true })}
onChangeText={text => setValue("description", text)}
multiline={true}
style={styles.descInput}
placeholder="Nos descreva com detalhes sobre o caso do seu Pet"></TextInput>
</KeyboardAvoidingView>
<View style={styles.buttons}>
<TouchableOpacity onPress={toogleModal} style={styles.ButtonClose}><Text style={{ color: 'white', fontFamily: 'Montserrat_400Regular' }}>Fechar</Text></TouchableOpacity>
<TouchableOpacity onPress={handleSubmit(onSubmit)} style={styles.ButtonClose}><Text style={{ color: 'white', fontFamily: 'Montserrat_400Regular' }}> Criar</Text></TouchableOpacity>
</View>
</View>
perhaps useFieldArray will be the better usage here since you are talking about the insert.
https://react-hook-form.com/api#useFieldArray
you can then use the insert action. eg:
import React from "react";
import { useForm, useFieldArray } from "react-hook-form";
function App() {
const { register, control, handleSubmit, reset, trigger, setError } = useForm({
// defaultValues: {}; you can populate the fields by this attribute
});
const { fields, append, prepend, remove, swap, move, insert } = useFieldArray({
control,
name: "test"
});
return (
<form onSubmit={handleSubmit(data => console.log(data))}>
<ul>
{fields.map((item, index) => (
<li key={item.id}>
<input
name={`test[${index}].firstName`}
ref={register()}
defaultValue={item.firstName} // make sure to set up defaultValue
/>
<Controller
as={<input />}
name={`test[${index}].lastName`}
control={control}
defaultValue={item.lastName} // make sure to set up defaultValue
/>
<button type="button" onClick={() => remove(index)}>Delete</button>
</li>
))}
</ul>
<button
type="button"
onClick={() => insert(1, { firstName: "appendBill", lastName: "appendLuo" })}
>
append
</button>
<input type="submit" />
</form>
);
}
I am really a beginner.
in renderItem ()
If {item.value} is 10 or less, I want to render the output as "Text".
How can I do this?
Thank you for reading the question. I will study hard
I pray that you will be safe and healthy from the corona virus.
renderItem = ({item}) => {
return(
<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
<View style={{marginBottom:10}}>
<Text>
{item.from}
{item.to}
{item.value}
</Text>
</View>
</View>
)
}
componentDidMount(){
const url = 'http://api-ropsten.etherscan.io/api?module=account&action=txlist&address=0x3A19E068Ea11b4D10D4516823eA9482fE70F1c52&startblock=0&endblock=99999999&sort=asc&apikey=IQN5KP8AKJ9WFTYNGZRJE7W3QHXPT4S65H'
fetch(url)
.then((response)=>response.json())
.then((responseJson) => {
this.setState({
dataSource:responseJson.result
})
})
.catch((error)=>{
console.log(error)
})
}
render(){
return(
<View style={{flex:1,justifyContent:'center', alignItems:'center'}}>
<FlatList
data={this.state.dataSource}
renderItem={this.renderItem}
/>
</View>
)
}
}
you need learn javascript and es6 specially, will help you a lot in future. For now you can check in renderItem method if value is less than 10 or not and then return the desired output.
renderItem = ({item}) => {
if(item.value < 10){
return(
<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
<View style={{marginBottom:10}}>
<Text>
{The text you want}
</Text>
</View>
</View>)
} else {
return <View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
<View style={{marginBottom:10}}>
<Text>
{some value}
</Text>
</View>
</View>
}
I have a endusers page where I fetch from an api and how the results in a flatlist as listitem.
I want to have one page for each user which shows their info but without creating userX.js for each user. So there should be only 1 page which is dynamically.
My Endusers.js View:
return (
<View style={styles.container}>
<View style={styles.headerContainer}>
<SearchBar
showLoading
placeholder={`Suchen: Name, Email oder Land...`}
lightTheme
round
onChangeText={text => this.searchFilterFunction(text)} />
</View>
<View style={styles.listContainer}>
<FlatList
style={styles.list}
data={this.state.data}
renderItem={({ item }) =>
<ListItem
titleStyle={styles.item}
subtitleStyle={styles.item}
title={`${item.strName} | ${item.strLand}`}
subtitle={`${item.strEmail}`}
containerStyle={{ borderBottomWidth: 0 }}
onPress={() => this.props.navigation.push('Userpage')}
/>}
keyExtractor={id => id}
/>
</View>
</View>
)
My Fetch method:
fetch(url)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
data: upper(responseJson.sort((a, b) => (a.strName - b.strName))),
loading: false,
error: responseJson.error
})
this.searchArray = responseJson;
})
.catch((error) => {
console.log(error)
})
My Constructor:
constructor() {
super()
this.state = {
loading: true,
data: [],
error: null
}
this.searchArray = [];
}
In Endusers.js View when I click on listitem the Userpage.js should show with the info of the clicked user.
How should I go on about this problem? What are the keywords I need to
google/research to find a solution? I'm not her to just copy paste so
please don't get this question wrong^^
You can send params when you push the navigation:
this.props.navigator.push({
component: MyScene,
title: 'Scene ' + nextIndex,
passProps: {index: nextIndex},
});
You can send as passProps your item which i guess contains the details regarding your User, like this:
passProps: {item: item}
Hope I helped, and more details on react-native documentation https://facebook.github.io/react-native/docs/navigation.
I am mapping json data and can console.log my result, but I can't insert those values in the render.
Here is the code I have for my render:
data_use = responseJson;
const result_id = data_use.map(function(val) {
return val.id;
}).join(',');
console.log(result_id);
render(){
return(
<View style = { styles.MainContainer }>
<View>
<Card>
<View>
<Text>{result_id}</Text>
</View>
</Card>
</View>
</View>
);
}
The error that I am getting is ReferenceError: result_id is not defined. Which is odd because it is defined?
This approach will be useful if the data is loaded from a server.
constructor(props) {
super(props);
this.state = {
data : []
};
}
componentDidMount() {
// Your code to fetch data from server
this.setState({ data: your_array_from_fetch });
}
render(){
return(
<View style={ styles.MainContainer }>
<View>
<Card>
<View>
{
this.state.data.length > 0 ?
this.state.data.map((val, index) => {
return (
<Text key={index}>val.id</Text>
);
} ).join(',');
: null
}
</View>
</Card>
</View>
</View>
);
}
I made few assumption from my side and I believe this is what you want! If any issue write that down below.
EDIT:
Yoganode issue can be fixed by testing if the data array length is greater than zero. This usually happens when render does not return anything.
I used componentDidMount instead of componentWillMount because componentWillMount is deprecated.
Try this conditional render
{
this.state.data.length > 0 ?
this.state.data.map((val, index) => {
if (some_var == another_var) {
return (
<Text key={index}>val.id</Text>
);
}
}).join(',');
: null
}
Everything you did is correct but variable you declared outside render? How can it be accessed in render
render(){
//considering array of objects in "data_use" state
const result_id = this.state.data_use.map(function(val) {
return val.id;
}).join(',');
return(
<View style = { styles.MainContainer }>
<View>
<Card>
<View>
<Text>{result_id}</Text>
</View>
</Card>
</View>
</View>
);
}
I am new to React Native, and want to get the nested object from json. Here is my code. And I can get succesfuly data.phone but always get this if I try to get data.name.title or etc.
undefined is not an object
Here is my code.
class Dictionary extends Component {
// Initialize the hardcoded data
constructor(props) {
super(props);
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
dataSource: ds.cloneWithRows([
'John', 'Joel', 'James', 'Jimmy', 'Jackson', 'Jillian', 'Julie', 'Devin'
])
};
fetch('http://api.randomuser.me/?results=50')
.then((response) => response.json())
.then((responseJson) => {
//return responseJson.movies;
console.log( responseJson.results );
this.setState({
dataSource: ds.cloneWithRows(responseJson.results),
loaded:false,
})
})
.catch((error) => {
console.error(error);
});
}
render() {
return (
<View
style={styles.container}>
<ListView
dataSource={this.state.dataSource}
renderRow={(data) =>
<View>
<Text>
{data.phone}
</Text>
<Text>
{data.name.title}
</Text>
</View>
}
renderSeparator={(sectionId, rowId) => <View key={rowId} style={styles.separator} />}
/>
</View>
);
}
}
How can I get the name.title?
Thanks
And here is the json data from randomuser.me
{"results":[{"gender":"female","name":{"title":"miss","first":"abby","last":"perkins"},"location":{"street":"9542 highfield road","city":"ely","state":"herefordshire","postcode":"J9 2ZJ"},"email":"abby.perkins#example.com","login":{"username":"redcat541","password":"1026","salt":"LIsOByBg","md5":"2890bf50a87289f7f3664840e2c47fe3","sha1":"1944896ba6cc78ad32dcf927dc5c9226d2f9e050","sha256":"9013be19c91195788009cc545f8a2be4494687dc29b155513022ce9157b73785"},"dob":"1959-05-20 07:03:41","registered":"2006-07-10 01:28:56","phone":"0101 716 4694","cell":"0738-649-138","id":{"name":"NINO","value":"BC 35 80 42 Q"},"picture":{"large":"https://randomuser.me/api/portraits/women/54.jpg","medium":"https://randomuser.me/api/portraits/med/women/54.jpg","thumbnail":"https://randomuser.me/api/portraits/thumb/women/54.jpg"},"nat":"GB"}],"info":{"seed":"2e632bbc13c85cb2","results":1,"page":1,"version":"1.1"}}
when I console.log(data.name) I get this {"title":"miss","first":"abby","last":"perkins"} and so on on every Iteration i get different names. So i guess there is no need in data[0] - it looks like everything is ok with getting the proper data object. just need to access data.name.title but no luck with it. Sorry, it pretty confusing for me this time as every prev time there were no problems with any json obj or array
This is caused by the constructor, but I don't know why.
Just pass an empty array and it will work.
this.state = {
dataSource: ds.cloneWithRows([])
};
You can do this too:
this.state = {
dataSource: ds.cloneWithRows([{name: "Ahmed"}])
};
See here for more information:
https://facebook.github.io/react-native/docs/listviewdatasource.html#clonewithrows
Its because your {data.name.title} is directly in view tag. Place that in <Text> component like this:
<ListView
dataSource={this.state.dataSource}
renderRow={(data) =>
<View>
<Text>
{data.phone}
</Text>
<Text>
{data.name.title}
</Text>
</View>
}
renderSeparator={(sectionId, rowId) => <View key={rowId} style={styles.separator} />}
/>