I am working on an app and I want to pass in a key from a dictionary to a child screen. I have the dictionary in the parent, the code below shows what I want to accomplish
import ImageDetail from "../components/ImageDetail";
var Salad = {
GreekSalad: ["Greek Salad", "Romaine lettuce, cucumber, onion, olives, tomatoes, bell peppers, feta cheese dressed with lemon, salt, and olive oil dressing",require('../../assets/greeksalad.jpg'), 10],
ArabicSalad: ["Arabic Salad", "Diced cucumbers, tomato, green onion, parsley dressed with lemon, salt, and olive oil dressing",require('../../assets/arabicsalad.jpg'), 8],
Tabula: ["Tabouli", "fine chopped parsley, cracked wheat, tomatoes, and cucumber dressed with lemon salt and olive oil dressing", 8],
KHSS: ["KH Special Salad", "Romaine lettuce, cucumbers, onions, tomatoes, onions, apples, mint, bell peppers, sunflower seeds, and zaatar dressed with lemon, salt, and olive oil dressing", 12],
LSCup: ["Lentil Soup", "Flavorful lentil, carrot, and onion pureed soup(Cup 8oz)", 5],
LSBowl: ["Lentil Soup", "Flavorful lentil, carrot, and onion pureed soup(Bowl 12oz)", 7]
};
The next portion of the code is the part that is difficult for me to finish, specifically the TouchableOpacity passing the Salads. GreekSalad key and value into the next page
const Salads = () => {
return (
<View>
<ScrollView>
<View style={styles.backGround}>
<View style={styles.container}>
<Image style={styles.logostyle} source={require('../../assets/KabobHouseLogo.jpg')}/>
</View>
<Text style={styles.title}>Salads{"\n"}</Text>
<View style={styles.container1}>
<TouchableOpacity onPress={(Salad.GreekSalad) => {props.navigation.navigate("InnerMenu")}}>
<ImageDetail title={Salad.GreekSalad[0]} description={Salad.GreekSalad[1]} imageSource={Salad.GreekSalad[2]} price={Salad.GreekSalad[3]}/>
</TouchableOpacity>
<ImageDetail title={Salad.ArabicSalad[0]} description={Salad.ArabicSalad[1]} imageSource={Salad.ArabicSalad[2]} price={Salad.ArabicSalad[3]}/>
<ImageDetail title={Salad.Tabula[0]} description={Salad.Tabula[1]} imageSource={require('../../assets/KabobHouseLogo.jpg')} price={Salad.Tabula[2]}/>
<ImageDetail title={Salad.KHSS[0]} description={Salad.KHSS[1]} imageSource={require('../../assets/KabobHouseLogo.jpg')} price={Salad.KHSS[2]}/>
This is how you pass values in React Navigation to the next screen
// navigation.navigate('RouteName', { /* params go here */ })
const nextScreen = ()=>{
props.navigation.navigate("InnerMenu",{saladKey:Salad.GreekSalad[1]})
}
Then pass the function into onPress
<TouchableOpacity onPress={nextScreen}>
<ImageDetail title={Salad.GreekSalad[0]} description={Salad.GreekSalad[1]} imageSource={Salad.GreekSalad[2]} price={Salad.GreekSalad[3]}/>
</TouchableOpacity>
This is how you access them in the next screen
const childScreen = (props)=>{
const saladKey = props.route.params.saladKey;
}
Lastly I recommended that you don't make a habit of passing around values between screens. Instead for most cases you can use a thing called useContext which lets you share state between all your screens. Read more here (https://dmitripavlutin.com/react-context-and-usecontext/)
Related
This is a long issue so I would go thru one by one:
This are the part of the contents of my firebase realtime database:
{
"food": {
"Bakery": {
"Bakery Cuisine": {
"Description": "Within North Spine Plaza",
"Halal": "Yes",
"Location": "50 Nanyang Ave, #01-20 North Spine Plaza, Singapore 639798",
"OH": "Mon - Sat : 8 AM to 7 PM, Sun Closed"
},
"TestBakery": {
"Description": "A",
"Halal": "B",
"Location": "C",
"OH": "D"
}
},
"Beverage": {
"Beverage": {
"Description": "Within the South Spine food court",
"Halal": "No",
"Location": "21 Nanyang Link, Singapore 637371",
"OH": "Mon - Fri: 7 30 am to 8 pm, Sat - Sun/PH Closed"
},
"Beverages": {
"Description": "Within North Spine Koufu",
"Halal": "No",
"Location": "76 Nanyang Dr, #02-03 North Spine Plaza, Singapore 637331",
"OH": "Mon - Fri : 7 am to 8 pm, Sat : 7 am to 3 pm, Sun Closed"
},
"Boost": {
"Description": "Within North Spine Plaza",
"Halal": "No",
"Location": "50 Nanyang Ave, #01-11 North Spine Plaza, Singapore 639798",
"OH": "Mon - Fri : 10 am to 9 pm, Sat - Sun: 10 am to 6 pm"
},
As you can see from the database,
1st level: it is food
2nd level: it has Bakery & Beverage . This are what I called cuisine. It might be a bit weird but there are cuisine such as Japanese and many more
3rd level: It has names like Bakery Cuisine. This are the shop names under the cuisine.
4th level: Here contains the details of the shop
Next I will explain the tasks I am did and trying to do but failed.
Step 1: Page (Home) contains a drop down list that
has contains all the different cuisines
(Level 2 of my database) and a search button
What the user can do here is to choose a cuisine and press search.
What is done at the code is this cuisine value
is passed down to another page (SubScreen1).
[Complete]
Step 2: Page (SubScreen1) receives the cuisine
value from page (Homepage). It
then search the database for the shop
names under that cuisine. Eg searching
URL will be food/Bakery. According to
the database I pasted on top, there are
2 shop names under Bakery which are
Bakery Cuisine & TestBakery. Now, I will
display this 2 shop names in the screen as buttons.
[Complete]
Step 3: User at page (SubScreen1) now gets to
make a decision. To pick one of the shop
name and press it and will be transfer to another page (SubScreen3)
At the code side, this shop name's value that the user
has pressed is passed on to another page(SubScreen3).
[Complete]
Step 4: By now the variable that is being passed from page(Homepage)
to page (SubScreen3) has become cuisine/store name. Example
will be Bakery/Bakery Cuisine. Finally what I want to do
here is to extract out the details under Bakery Cuisine
and paste it on the page for the user to see. Including the name
Bakery Cuisine.
[Stuck]
The details are as follows:
"Bakery Cuisine": {
"Description": "Within North Spine Plaza",
"Halal": "Yes",
"Location": "50 Nanyang Ave, #01-20 North Spine Plaza, Singapore 639798",
"OH": "Mon - Sat : 8 AM to 7 PM, Sun Closed"
},
Here comes the problem:
When I reach this step and I log my query to the database, I get this
It is no longer in long string of words like the data in the database. This happens because my database query is to the lowest level right now. Example for this will be food/Bakery/Bakery Cuisine
Currently my code in the step 4(SubScreen3):
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native'
import React, {useEffect, useState} from 'react'
import {db} from '../firebase'
import {ref, onValue} from 'firebase/database'
import { useNavigation } from '#react-navigation/core'
const SubScreen3 = ({route}) => {
const paramKey = route.params.paramKey1
//const paramKey1 = route.params.paramKey2
console.log(paramKey)
//console.log(paramKey1)
const [todoData, setToDoData] = useState([])
useEffect (() => {
const starCountRef = ref(db, "food/" + paramKey );
onValue(starCountRef, (snapshot) =>{
const data = snapshot.val();
const newPosts = Object.keys(data).map(key =>({
id:key,
...data[key]
})
);
console.log(newPosts);
setToDoData(newPosts);
})
}, [])
return (
<View style = {styles.container}>
<Text style = {styles.header}></Text>
{
todoData.map((item,index) => {
return(
<View key ={index}>
<Text style = {styles.header}>{item.id}</Text>
<Text style ={styles.text}>{item.Location}</Text>
<Text style ={styles.text}>{item.Description}</Text>
<Text style ={styles.text}>{item.Halal}</Text>
<Text style ={styles.text}>{item.OH}</Text>
</View>
)
})
}
<TouchableOpacity
//onPress={() => navigation.navigate("SubScreen1", {paramKey:value})}
style = {styles.button}
>
<Text style = {styles.buttonText}>How to go?</Text>
</TouchableOpacity>
<TouchableOpacity
//onPress={setRandomValue}
style = {styles.button}
>
<Text style = {styles.buttonText}>Reviews</Text>
</TouchableOpacity>
</View>
So my questions:
1st - How do I change my code to get the long strings of words out? Eg, I cannot use item.Description to get the long string of Within North Spine Plaza as nothing appears.
2nd - How do I change my code so I can get the shop name out. In this case it is Bakery Cuisine
Tried the solution:
Code (SubScreen3):
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native'
import React, {useEffect, useState} from 'react'
import {db} from '../firebase'
import {ref, onValue} from 'firebase/database'
import { useNavigation } from '#react-navigation/core'
const SubScreen3 = ({route}) => {
const paramKey = route.params.paramKey1
//const paramKey1 = route.params.paramKey2
//console.log(paramKey)
//console.log(paramKey1)
const [todoData, setToDoData] = useState([])
useEffect (() => {
const starCountRef = ref(db, "food/" + paramKey );
onValue(starCountRef, (snapshot) =>{
snapshot.forEach((child) => {
console.log(child.key); // "Bakery Cuisine", "TestBakery"
console.log(child.val().Description); // "Within North Spine Plaza", "A"
});
})
}, [])
return (
<View style = {styles.container}>
<Text style = {styles.header}></Text>
{
todoData.map((item,index) => {
return(
<View key ={index}>
<Text style = {styles.header}>{item.id}</Text>
<Text style ={styles.text}>{item.Location}</Text>
<Text style ={styles.text}>{item.Description}</Text>
<Text style ={styles.text}>{item.Halal}</Text>
<Text style ={styles.text}>{item.OH}</Text>
</View>
)
})
}
<TouchableOpacity
//onPress={() => navigation.navigate("SubScreen1", {paramKey:value})}
style = {styles.button}
>
<Text style = {styles.buttonText}>How to go?</Text>
</TouchableOpacity>
<TouchableOpacity
//onPress={setRandomValue}
style = {styles.button}
>
<Text style = {styles.buttonText}>Reviews</Text>
</TouchableOpacity>
</View>
)
}
export default SubScreen3
Here are the logs:
It is not logging correctly:
console.log(child.key); logs the following: Description, Halal, OH, Location
console.log(child.val().Description); gives me undefined
What I want to achieve at this page (SubScreen3) is getting the following:
Name of the stall
Description of the stall
Halal of the stall
Location of the stall
OH of the stall
To load the data for one of your food child nodes and then navigate the snapshot in your application code, you can do:
const foodRef = ref(db, "food/Bakery");
onValue(foodRef, (snapshot) => {
snapshot.forEach((child) => {
console.log(child.key); // "Bakery Cuisine", "TestBakery"
console.log(child.val().Description); // "Within North Spine Plaza", "A"
});
})
I'm applying star rating to my react app.
so I have lists of star components. Once I click on rating it's applying for the all components.
Like I do star rating to first food, then it gets apply for all foods also.
I want to handle each food rating independently.
Can someone tell me where I'm going wrong ?
befor rating
after rating for one food
here is my..
import React, { useCallback, useEffect } from "react";
import "./styles.css";
import { Rating } from 'react-simple-star-rating'
import Star from './Start';
export default function App() {
const [category, setCategory] = React.useState("Indian");
const [rating, setRating] = React.useState(3);
const handleChange = (value) => {
setRating(value);
}
const Food = {
Indian: [
{
name: "Misal Pav",
description:
"Misal pav is a popular Maharashtrian street food of usal (sprouts curry) topped with onions, tomatoes, farsan (fried savory mixture), lemon juice, coriander leaves and served with a side of soft pav (Indian dinner rolls). The sprouts curry is made from moth bean sprouts. This misal recipe is a tasty and filling vegan dish that can be served as breakfast, lunch or brunch.",
rating: 5,
},
{
name: "Vada Pav",
description:
"Vada pav is a savory dinner roll stuffed with fried mashed and spiced potato fritters. It is a popular vegan street food snack eaten in Mumbai and rest of Maharashtra. This dish is full of flavors and various textures!",
rating: 1,
},
{
name: "Masala Dosa",
description:
"Masala Dosa / dosey / dosai is a variation of the popular South Indian dosa which has its origins in Tuluva Udupi cuisine of Karnataka. It is made from rice, lentils, potato, fenugreek, ghee and curry leaves, and served with chutneys and sambar. It is popular in South India.",
rating: 1,
}
],
Chinese: [
{
name: "Noodles",
description:
"Chinese noodles vary widely according to the region of production, ingredients, shape or width, and manner of preparation. Noodles were invented in China, and are an essential ingredient and staple in Chinese cuisine. They are an important part of most regional cuisines within China, and other countries with sizable overseas Chinese populations.",
rating: 2,
},
{
name: "chilly chicken ",
description:
"Chilli chicken is a popular Indo-Chinese dish of chicken of Hakka Chinese heritage. In India, this may include a variety of dry chicken preparations.",
rating: 2,
},
{
name: "Manchurian",
description:
"Veg Manchurian is a tasty Indo Chinese dish of fried veggie balls in a spicy, sweet and tangy sauce. ",
rating: 2,
}
],
Italian: [
{
name: "Pizza",
description:
"Though a slab of flat bread served with oil and spices was around long before the unification Italy, there’s perhaps no dish that is as common or as representative of the country as the humble pizza.",
rating: 3,
},
{
name: "Pasta",
description:
"pasta, any of several starchy food preparations (pasta alimentaria) frequently associated with Italian cuisine and made from semolina, the granular product obtained from the endosperm of a type of wheat called durum, and containing a large proportion of gluten (elastic protein).",
rating: 3,
},
{
name: "Lasagna",
description:
"Lasagna is a wide, flat pasta noodle, usually baked in layers in the oven. Like most Italian dishes, its origins are hotly contested, but we can at least say that’s its stronghold is in the region of Emilia-Romagna, where it transformed from a poor man’s food to a rich meal filled with the ragù, or meat sauce.",
rating: 3,
}
]
};
const handleChangeButton = (cat) => {
setCategory(cat);
};
useEffect(() => {
setCategory(category);
}, [setCategory, category]);
return (
<div className="App">
<h1>
<img
className="logo"
src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJYAAACWCAMAAAAL34HQAAABelBMVEX////+/v7/tABHIQzqLir/tgDoAAD/uAD/uwDqKyc6AAAAAADqIBv1t7Y0AAApAAD/vwDqJiL73dwtAABEGwDx7+3s6efMxcL59/YjAADb3NwdAADf29nV0M7h4uLpGhTfAADzl5b4xcSQgXtpVFLDvLqGdW9kSD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RP7N9duCsKEK/+FyJOZgh6WsWTAAAAAElFTkSuQmCC"
alt="Good Food"
/>
Good Food
</h1>
<p>Checkout my Favourite food items here ...</p>
<div className="btn-container">
{Object.keys(Food).map((cat, i) => (
<button
key={i}
className={category === cat ? "active" : ""}
onClick={() => handleChangeButton(cat)}
>
{cat}{" "}
</button>
))}
</div>
<h2>List</h2>
<div className="list-container">
{Food[category].map((foodie, i) => (
<div className="list-item" key={i}>
<Star
count={5}
size={40}
value={rating}
activeColor={'red'}
inactiveColor={'#ddd'}
onChange={handleChange} />
<h5>{foodie.description}</h5>
</div>
))}
</div>
</div>
);
}
It's because you are getting Star component's value props from one source which is rating.
You need to have an individual value for each Star components.
Replace your Star component with:
<Star
count={5}
size={40}
value={foodie.rating}
activeColor={'red'}
inactiveColor={'#ddd'}
onChange={handleChange}
/>
Edit:
Edit:
You also need to put the Food object inside a useState so you can edit the ratings for each food categories.
ex:
const [food, setFood] = useState({
Indian: [
{
name: "Misal Pav",
description:
"Misal pav is a popular Maharashtrian street food of usal (sprouts curry) topped with onions, tomatoes, farsan (fried savory mixture), lemon juice, coriander leaves and served with a side of soft pav (Indian dinner rolls). The sprouts curry is made from moth bean sprouts. This misal recipe is a tasty and filling vegan dish that can be served as breakfast, lunch or brunch.",
rating: 5,
},
{
name: "Vada Pav",
description:
"Vada pav is a savory dinner roll stuffed with fried mashed and spiced potato fritters. It is a popular vegan street food snack eaten in Mumbai and rest of Maharashtra. This dish is full of flavors and various textures!",
rating: 1,
},
{
name: "Masala Dosa",
description:
"Masala Dosa / dosey / dosai is a variation of the popular South Indian dosa which has its origins in Tuluva Udupi cuisine of Karnataka. It is made from rice, lentils, potato, fenugreek, ghee and curry leaves, and served with chutneys and sambar. It is popular in South India.",
rating: 1,
}
],
...
and to set Rating you can do:
const setRating = (type: string, food: string, rating: number) => {
setFood((prevFood) => {
return {
...prevFood,
[type]: prevFood[type].map((foodData: any) => {
if (foodData.name === food) {
return {
...foodData,
rating
}
}
return foodData;
})
}
})
}
This is happening because you are updating you state rating, and using this state in all your lists.
<Star
count={5}
size={40}
value={rating} // <----- state that get's updated
activeColor={'red'}
inactiveColor={'#ddd'}
onChange={handleChange} />
Instead you need to update the FOOD object. One way would be you can code your onChange such that it finds the element for which you selected starts, and based on that it can update the ratings property and then you can use that rating propery in component.
<Star
count={5}
size={40}
value={foodie.rating} <-- since you will update the FOOD object you'll get desired result.
activeColor={'red'}
inactiveColor={'#ddd'}
onChange={handleChange} />
You can update rating independently via useState
Here you don't have any unique id so i find name.
key refers to food[key] ,
ob refers which rating has to updated just pass entire object, like food[key][position]
const handleUpdateRating = (key, ob) => {
setFood((prevData) => ({
...prevData ,
[key]:prevData.[key].map((obj) =>
obj.name === ob.name ? {...obj , rating:ob.rating + 1} : obj
)
}))
};
I currently am building a fitness website and am looking to use Mantine UI accordion component which is based off Typescript. I built my react project with javascript. Is there a way to create a .tsx file and call it into my app.js file?
Here's the error I am currently receiving. Am I missing the export on the Accordian code?
Module not found: Error: Can't resolve './components/Faq' in '/Users/rodriguezmedia/Desktop/blended/src'
import { Group, Avatar, Text, Accordion } from '#mantine/core';
import React from 'react';
const charactersList = [
{
image: 'https://img.icons8.com/clouds/256/000000/futurama-bender.png',
label: 'Bender Bending Rodríguez',
description: 'Fascinated with cooking, though has no sense of taste',
content: "Bender Bending Rodríguez, (born September 4, 2996), designated Bending Unit 22, and commonly known as Bender, is a bending unit created by a division of MomCorp in Tijuana, Mexico, and his serial number is 2716057. His mugshot id number is 01473. He is Fry's best friend.",
},
{
image: 'https://img.icons8.com/clouds/256/000000/futurama-mom.png',
label: 'Carol Miller',
description: 'One of the richest people on Earth',
content: "Carol Miller (born January 30, 2880), better known as Mom, is the evil chief executive officer and shareholder of 99.7% of Momcorp, one of the largest industrial conglomerates in the universe and the source of most of Earth's robots. She is also one of the main antagonists of the Futurama series.",
},
{
image: 'https://img.icons8.com/clouds/256/000000/homer-simpson.png',
label: 'Homer Simpson',
description: 'Overweight, lazy, and often ignorant',
content: 'Homer Jay Simpson (born May 12) is the main protagonist and one of the five main characters of The Simpsons series(or show). He is the spouse of Marge Simpson and father of Bart, Lisa and Maggie Simpson.',
},
{
image: 'https://img.icons8.com/clouds/256/000000/spongebob-squarepants.png',
label: 'Spongebob Squarepants',
description: 'Not just a sponge',
content: 'SpongeBob is a childish and joyful sea sponge who lives in a pineapple with his pet snail Gary in the underwater city of Bikini Bottom. He works as a fry cook at the Krusty Krab, a job which he is exceptionally skilled at and enjoys thoroughly. ',
},
]
interface AccordionLabelProps {
label: string;
image: string;
description: string;
}
function AccordionLabel({ label, image, description }: AccordionLabelProps) {
return (
<Group noWrap>
<Avatar src={image} radius="xl" size="lg" />
<div>
<Text>{label}</Text>
<Text size="sm" color="dimmed" weight={400}>
{description}
</Text>
</div>
</Group>
);
}
function Demo() {
const items = charactersList.map((item) => (
<Accordion.Item label={<AccordionLabel {...item} />} key={item.label}>
<Text size="sm">{item.content}</Text>
</Accordion.Item>
));
return (
<Accordion initialItem={-1} iconPosition="right">
{items}
</Accordion>
);
}
Is there a way to create a .tsx file and call it into my app.js file?
No. You need to delete all of the typescript types (interfaces ...etc) and rename the file to .js.
You need a typescript (compiler) to convert the .tsx file into .js. Otherwise you cannot use .tsx files, since browser can only parse js.
How can I render post data on one page using props if someone clicks the post div on the home page then it reaches the post data page by using a link which I give in the backend { like if the link is the same then and only then render post data on the (sectioninner.js) } like movies website
Sectioninner.js
import React, { useState, useEffect,useRef } from 'react'
import { Link, useParams } from "react-router-dom";
function Sectioninner(post) {
const [loading, setLoading] = useState(false);
const { title } = useParams();
const componentMounted = useRef(true);
useEffect(async () => {
setLoading(true);
const response = await fetch('http://localhost:5000/posts');
if (componentMounted.current) {
(await response.json());
setLoading(false);
}
return () => {
componentMounted.current = false;
}
}, []);
return (
<>
return (
<div key= {post._id}className="hey">
{
<>
<div className="downloadcontainer">
<div className="container12">
{/* Path */}
<p>Home » {post.HeadingTitle}</p>
{/* Categories */}
<p> {post.Categories}</p>
<h1>{post.HeadingTitle}</h1>
<div className='titlebelow'>
<span className='calender'>
<img className='imgcalender' src={calender} alt="Date Modified" /> <p className='publishedcount'>{post.datetime}</p>
</span>
<span className='comment'>
<img className='imgcomment' src={comment} alt="comments" /> <p className='commentcount'>Add a comment</p>
</span>
<span className='views'>
<img className='imgviews' src={views} alt="views" /> <p className='viewscount'>22,439 views</p>
</span>
</div>
</div>
</>
</div>
)
)}
</>
)
}
export default Sectioninner
in the database, i am using a link tag for rendering if the link is there then render post data else nothing to return
what should I do for implemented that result in my code
{
"code": 200,
"message": "post Added Sucessfully",
"addPosts": {
"link": "The-Boys-Season-01-02-(2019-2020)-Dual-Audio-{Hindi-English}-1080p-x264-||-1080p 10bit-||-Bluray ",
"title": "The Boys Season 01-02 (2019-2020) Dual Audio {Hindi-English} 1080p x264 || 1080p 10bit || Bluray ",
"image": "image_1649565125439.png",
"HeadingTitle": "Download The Boys Season 01-02 (2019-2020) Dual Audio {Hindi-English} 1080p x264 || 1080p 10bit || Bluray ",
"datetime": "08 April 2022",
"smallTitle": "Download The Boys Season 01-02 (2019-2020) Dual Audio {Hindi-English} 1080p x264 || 1080p 10bit || Bluray || WEB-",
"MoviesContent": "Parents need to know that The Boys is a dark comedy series about a world in which superheroes aren't actually the good guys. This means that the \"heroes\" in the show are constantly doing terrible things including, but not limited to, sexual assault and acts of terrorism. As a result, the show contains just about every type of adult content you can imagine -- simulated sex, male and female nudity,",
"allCategories": "1080P,2160P,WEB-DL",
"_id": "62525dc5b5254b12e0e08419",
"__v": 0
},
"image": "http://localhost:5000/image_1649565125439.png"
}
I am trying to dial a phone number if the user swipes on the phone icon in react Native. For e.g. if I have (999)-996-5432 on my phone then when user swipes the icon then this number should be automatically dialed. Below is my code for handleclick
export default class ServiceListDetails extends Component {
handleClick = (link) => {
Linking.canOpenURL(link).then(suppported => {
if (supported) {
Linking.openURL(link);
} else {
console.log('Don\'t know how to open URI: ' + link);
}
});
};
Below is the code where I am calling the handleClick from:
return(
<Text style={styles.Address1}>{item.addr} </Text>
<View style={styles.phoneImg}>
<TouchableOpacity
onPress={() => { this.handleClick('tel:${item.phone}')}}>
<Image source={require('../images/Phone.png')} style={styles.actionImage}/>
</TouchableOpacity>
<Text style={styles.Address1}>{item.phone}</Text>
</View>
)
item.phone is coming from my JSON file. Below is my JSON file:
[
{
"id":"2",
"fk": 1,
"addr": "123 test drive, Ring road test",
"phone": "(999)-345-7896"
},
{
"id":"3",
"fk": 1,
"addr": "123 test drive, Test Road",
"phone": "(951)-765-2222"
}
]
I already deployed the application on iPhone and tried to swipe the phone number and it is not doing anything. I know phone icon swiping wont work in emulator.
Any help will be greatly appreciated.
There is a typo error (suppported & supported). fix this and it will work
Linking.canOpenURL(link).then(suppported => {
if (supported) {