google react-places-autocomplete api restrict search suggestions to Australia / single country - reactjs

Hello I want to limit my search suggestions (and therefore limit a user to choose an Australian address) with react places autocomplete to addresses from Australia, and to note I have checked stack overflow for similar questions and none of them seem to work, here is an example of the suggestions I am currently getting that i would like to be only Australian Suggestions.
screen shot
here is what i think is the relevant code
import PlacesAutocomplete, {
geocodeByAddress,
getLatLng,
} from 'react-places-autocomplete';
<PlacesAutocomplete
fullWidth
className="search-bar"
value={address}
onChange={setAddress}
onSelect={handleSelect}
>
{({ getInputProps, suggestions, getSuggestionItemProps, loading }) => (
<div >
<input
style={{width:"100%" }}
{...getInputProps({
placeholder: 'Enter Job Address',
className: 'location-search-input',
})}
/>
<div className="autocomplete-dropdown-container"
key={suggestions.description}
>
{loading && <div>Loading...</div>}
{suggestions.map((suggestion, index)=> {
const className = suggestion.active
? 'suggestion-item--active'
: 'suggestion-item';
// inline style for demonstration purpose
const style = suggestion.active
? { backgroundColor: '#fafafa', cursor: 'pointer' }
: { backgroundColor: '#ffffff', cursor: 'pointer' };
return (
<div
key={index}
{...getSuggestionItemProps(suggestion, {
className,
style,
})}
>
<span>{suggestion.description }</span>
</div>
);
})}
</div>
</div>
)}
</PlacesAutocomplete>

try with this prop
searchOptions={{componentRestrictions: { country: ['au'] }}}

Related

Inline media queries using react

I have this section of code I am trying to render. At different viewports, the button styles change from underline to background color using a themeColor I pull from a JSON file with acting as my database in a sense. How do you write an 'else if' inline in react so when my state is "active" and the media query matches, the styles update accordingly?
const btnMobileStyle = useMediaQuery('(min-width: 375px)')
const btnTabletStyle = useMediaQuery('(min-width: 768px)')
const styles = {
buttonMobile: (btnMobileStyle) => ({
borderBottom: `2px solid ${themeColor}`,
}),
buttonTablet: (btnTabletStyle) => ({
borderBottom: 'none',
backgroundColor: `${themeColor}`,
}),
}
return (
<main className="main">
<div className="main__btn-container">
<button
style={overviewActive ? styles.buttonMobile(btnMobileStyle) : {}}
onClick={updateOverview}
className="main__btn"
>
Overview
</button>
<button
style={structureActive ? styles.buttonMobile(btnMobileStyle) : {}}
onClick={updateStructure}
className="main__btn"
>
Structure
</button>
<button
style={surfaceActive ? styles.buttonMobile(btnMobileStyle) : {}}
onClick={updateSurface}
className="main__btn"
>
Surface
</button>
</div>
I was able to solve the issue using this code:
const btnMobileStyle = useMediaQuery('(max-width: 768px)')
const styles = {
btnMobile: (btnMobileStyle) => ({
borderBottom: btnMobileStyle ? `2px solid ${themeColor}` : {},
backgroundColor: btnMobileStyle ? 'transparent' : themeColor,
}),
}
return (
<main className="main">
<div className="main__btn-container">
<button
style={overviewActive ? styles.btnMobile(btnMobileStyle) : {}}
onClick={updateOverview}
className="main__btn"
>
Overview
</button>
<button
style={structureActive ? styles.btnMobile(btnMobileStyle) : {}}
onClick={updateStructure}
className="main__btn"
>
Structure
</button>
<button
style={surfaceActive ? styles.btnMobile(btnMobileStyle) : {}}
onClick={updateSurface}
className="main__btn"
>
Surface
</button>
</div>
<div className="main__img-container">
<img
className="main__planet-img"
src={state.planetImg}
alt={state.planetName}
/>
<img
className={
surfaceActive
? 'main__planet-overlay main__planet-overlay--active'
: 'main__planet-overlay'
}
src={state.planetImgOverlay}
alt=""
/>
</div>

how to make update of form fields "data is from database" in react

I try to build a site similar to wikipedia and its Edit functionality trouble me
think I send some data from DB like this
{
"post":[
{"title":"SOME TITLE","date":"20-12-2021"},
{"title":"SOME TITLE 2","date":"20-11-2021"}
]
}
with this data I need to show data to user and as well option to edit as well
so this means title and date are in some sort state variable I guess
how to achieve this I don't know I make question right but please consider wikipedia edit feature as example
how to implement it in react
Thanks
import { Form, Input, Button, Col, Row } from "antd";
import { PlusOutlined } from "#ant-design/icons";
const minusStyle = {
position: "relative",
margin: "0 8px",
color: "#999",
fontSize: "24px",
cursor: "pointer",
transition: "all 0.3s",
};
const PanditComponent = ({
panditNamez,
panditContactz,
onChangeSetPanditName,
onChangeSetPanditContact,
}) => {
console.log(panditContactz,panditNamez,onChangeSetPanditContact,onChangeSetPanditName)
return (
<Form style={{ marginTop: "8px" }}>
<Row>
<Col span={11}>
<Form.Item onChange={onChangeSetPanditName}>
<Input value={panditNamez} placeholder="Pandit Name"></Input>
</Form.Item>
</Col>
<Col span={11}>
<Form.Item onChange={onChangeSetPanditContact}>
<Input value={panditContactz} placeholder="Pandit Contact"></Input>
</Form.Item>
</Col>
<Col span={2}>
<Button icon={<PlusOutlined />} style={minusStyle}></Button>
</Col>
</Row>
</Form>
);
};
export default PanditComponent;
and this code to render the elements
data.pandit.map((p, index) => (
<PanditComponent
key={index}
panditNamez={panditDBItems[index]["name"]}
panditContactz={panditDBItems[index]["contact"]}
onChangeSetPanditName={(e) =>
// setPanditDBItems([{ name: "AAAAA", contact: "1234" }])
setPanditDBItems([{...panditDBItems,}])
}
onChangeSetPanditContact={(e) => console.log(e.target.value)}
/>
))
: null}
OK I solve this
if we break this question into simple words how to update state of array of objects like
panditDBItems = [{name:"aa",contact:12},{name:"b",contact:21}]
we can use do something
panditDBItems.map((p, index) => (
<PanditComponent
key={index}
panditNamez={panditDBItems[index]["name"]}
panditContactz={panditDBItems[index]["contact"]}
onChangeSetPanditName={(e) => {
let newPanditDBItems = [...panditDBItems];
newPanditDBItems[index]["name"] = e.target.value;
setPanditDBItems(newPanditDBItems);
}}
onChangeSetPanditContact={(e) => {
let newPanditDBItems = [...panditDBItems];
newPanditDBItems[index]["contact"] = e.target.value;
setPanditDBItems(newPanditDBItems);
}}
/>
)

React Final Form with react-places-autocomplete

I've looked at a bunch of other similar questions, but none are answered!
So far I have created a standard record-level which looks like this: https://final-form.org/docs/react-final-form/examples/record-level-validation
I am using React Final Form with react-places-autocomplete. I want to include the selections of react-places-autocomplete to show in the values as seen in the link above, when you enter information into the fields.
I have tried to add the following code based on react-places-autocomplete:
<Field name="location">
{({input, meta}) => (
<PlacesAutocomplete
value={address}
onChange={setAddress}
onSelect={handleSelect}
>
{({ getInputProps, suggestions, getSuggestionItemProps, loading }) => (
<div>
<p> latitude: {coordinates.lat}</p>
<p> longitude: {coordinates.lng}</p>
<input
{...input}
{...getInputProps({
placeholder: 'Search Places ...',
className: 'location-search-input',
})}
/>
<div className="autocomplete-dropdown-container">
{loading && <div>Loading...</div>}
{suggestions.map(suggestion => {
const className = suggestion.active
? 'suggestion-item--active'
: 'suggestion-item';
// inline style for demonstration purpose
const style = suggestion.active
? { backgroundColor: '#fafafa', cursor: 'pointer' }
: { backgroundColor: '#ffffff', cursor: 'pointer' };
return (
<div
{...getSuggestionItemProps(suggestion, {
className,
style,
})}
>
<span>{suggestion.description}</span>
</div>
);
})}
</div>
</div>
)}
</PlacesAutocomplete>
)}
</Field>
I'm wondering how I add the input of the placeautocomplete into this value here:
<pre>{JSON.stringify(values, undefined, 2)}</pre>
Sorry my answer is old, but try using react-google-places-autocomplete. Much better here is how you can use it....
<Field name="city">
{({ input, meta }) => (
<div style={{ width: '100%' }}>
<GooglePlacesAutocomplete
selectProps={{
value: input.value,
onChange: e => {
input.onChange(e.label)
},
}}
apiKey={GOOGLE_API_KEY}
autocompletionRequest={{
componentRestrictions: {
// country: [values.group_country && values.group_country.value]
country: ['CA', 'GB', 'US']
},
types:['(cities)']
}}
/>
{meta.error && meta.touched &&
<span className="text-danger small block">{meta.error}</span>}
</div>
)}
</Field>
The answer is really help but I found the input field was empty after I selected the address so I removed one line "value: input.value," it works for me.

Even After Enabling the Billing Account, I am still getting "Status: OVER_QUERY_LIMIT" while using google maps places api

billing information that it is enabled
I have enabled billing, but after using for a very few time and making very few requests I am getting:
You have exceeded your daily request quota for this API. If you did not set a custom daily request quota, verify your project has an active billing account: http://g.co/dev/maps-no-account For more information on usage limits and the Google Maps JavaScript API services please see: https://developers.google.com/maps/documentation/javascript/usage"
[react-places-autocomplete]: error happened when fetching data from Google Maps API.
Please check the docs here (https://developers.google.com/maps/documentation/javascript/places#place_details_responses)
Status: OVER_QUERY_LIMIT
Can someone please help to how to get rid of this problem?
I am using React js and my script code in public/index.html is
<script src="https://maps.googleapis.com/maps/api/js?key=MY_KEY_HERE&libraries=places"></script>
actually in the place of MY_KEY_HERE i am using the key i have generated and it worked super fine for 1 hr and later it is showing this error
and also my code for selecting places is
import React, { Component } from 'react';
import Toper3 from './Toper3';
import { MDBContainer, MDBRow, MDBCol, MDBBtn, MDBInput,MDBCard, MDBCardBody } from 'mdbreact';
import { Fragment } from 'react';
import axios from 'axios';
import PlacesAutocomplete, { geocodeByAddress, geocodeByPlaceId, getLatLng } from 'react-places-autocomplete';
import TimeField from 'react-simple-timefield';
const isObject = val => {
return typeof val === 'object' && val !== null;
};
const classnames = (...args) => {
const classes = [];
args.forEach(arg => {
if (typeof arg === 'string') {
classes.push(arg);
} else if (isObject(arg)) {
Object.keys(arg).forEach(key => {
if (arg[key]) {
classes.push(key);
}
});
} else {
throw new Error(
'`classnames` only accepts string or object as arguments'
);
}
});
return classes.join(' ');
};
class FindaRide extends Component {
constructor(props) {
super(props);
this.state = {
info : [],
source: '',
post_address_obj: {},
errorMessage: '',
latitude: null,
longitude: null,
isGeocoding: false,
d_post_address_obj: {},
d_errorMessage: '',
d_latitude: null,
d_longitude: null,
d_isGeocoding: false,
destination : ''
}
}
handleSourceAddressChange = address => {
// console.log(address);
this.setState({
source: address,
latitude: null,
longitude: null,
errorMessage: ""
});
};
handleDestinationAddressChange = address => {
// console.log(address);
this.setState({
destination: address,
d_latitude: null,
d_longitude: null,
d_errorMessage: ""
});
};
refine(){
alert("refinement");
const result = this.state.info.filter(word => word.source ==this.state.source&&word.destination==this.state.destination);
console.log("filtered "+result.length);
this.props.history.push({pathname : `findlist`, state : {details : this.props.location.state.details,info : this.state.info}});
}
handleSubmit = (event) => {
event.preventDefault();
axios.get('http://127.0.0.1:8000/api2/')
.then(res=>{
this.setState({
info : res.data
});
//console.log(res.data);
this.refine();
})
}
render() {
return (
<div>
<Toper3 >{this.props.location.state.details.firstname} {this.props.location.state.details.lastname}</Toper3>
<br/>
<MDBContainer>
<MDBRow>
<MDBCol md="6" className="mb-4" > {/*style={{ maxWidth: "22rem" }}*/}
<MDBCard color="indigo" text="white" className="text-center" align="center" style={{ maxWidth: "22rem" }}>
<MDBCardBody align = "center" >
FILL IN THE DETAILS TO FIND A RIDE
</MDBCardBody>
</MDBCard>
</MDBCol>
</MDBRow>
<form onSubmit={this.handleSubmit}>
<MDBRow>
<MDBCol md="6" className="mb-4">
<label> Source </label>
<PlacesAutocomplete
value={this.state.source}
onChange={this.handleSourceAddressChange}
>
{({ getInputProps, suggestions, getSuggestionItemProps }) => {
return (
<div className="Demo__search-bar-container">
<div className="Demo__search-input-container">
<input
{...getInputProps({
placeholder: "Tag the location",
className: "Demo__search-input"
})}
/>
{this.state.source.length > 0 && (
<button
className="Demo__clear-button"
onClick={this.handleCloseClick}
>
x
</button>
)}
</div>
{suggestions.length > 0 && (
<div className="Demo__autocomplete-container">
{suggestions.map(suggestion => {
const className = classnames("Demo__suggestion-item", {
"Demo__suggestion-item--active": suggestion.active
});
return (
/* eslint-disable react/jsx-key */
<div
{...getSuggestionItemProps(suggestion, {
className
})}
>
<strong>
{suggestion.formattedSuggestion.mainText}
</strong>{" "}
<small>
{suggestion.formattedSuggestion.secondaryText}
</small>
</div>
);
/* eslint-enable react/jsx-key */
})}
<div className="Demo__dropdown-footer">
<div>
<img
src="http://files.hostgator.co.in/hostgator254362/image/powered-by-google.png"
className="Demo__dropdown-footer-image"
/>
</div>
</div>
</div>
)}
</div>
);
}}
</PlacesAutocomplete>
</MDBCol>
</MDBRow>
<MDBRow>
<MDBCol md="6" className="mb-4">
<MDBInput
label="SOURCE"
group
type="text"
validate
error="wrong"
success="right"
value = {this.state.source}
style={{ maxWidth: "18rem" }}
//icon="envelope"
required
/>
</MDBCol>
</MDBRow>
<MDBRow>
<MDBCol md="6" className="mb-4">
<label> Destination </label>
<PlacesAutocomplete
value={this.state.destination}
onChange={this.handleDestinationAddressChange}
>
{({ getInputProps, suggestions, getSuggestionItemProps }) => {
return (
<div className="Demo__search-bar-container">
<div className="Demo__search-input-container">
<input
{...getInputProps({
placeholder: "Tag the location",
className: "Demo__search-input"
})}
/>
{this.state.destination.length > 0 && (
<button
className="Demo__clear-button"
onClick={this.handleCloseClick}
>
x
</button>
)}
</div>
{suggestions.length > 0 && (
<div className="Demo__autocomplete-container">
{suggestions.map(suggestion => {
const className = classnames("Demo__suggestion-item", {
"Demo__suggestion-item--active": suggestion.active
});
return (
/* eslint-disable react/jsx-key */
<div
{...getSuggestionItemProps(suggestion, {
className
})}
>
<strong>
{suggestion.formattedSuggestion.mainText}
</strong>{" "}
<small>
{suggestion.formattedSuggestion.secondaryText}
</small>
</div>
);
/* eslint-enable react/jsx-key */
})}
<div className="Demo__dropdown-footer">
<div>
<img
src="http://files.hostgator.co.in/hostgator254362/image/powered-by-google.png"
className="Demo__dropdown-footer-image"
/>
</div>
</div>
</div>
)}
</div>
);
}}
</PlacesAutocomplete>
</MDBCol>
</MDBRow>
<MDBRow>
<MDBCol md="6" className="mb-4">
<MDBInput
label="DESTINATION"
group
type="text"
validate
error="wrong"
success="right"
value = {this.state.destination}
style={{ maxWidth: "18rem" }}
//icon="envelope"
required
/>
</MDBCol>
</MDBRow>
<br/>
<br/>
<MDBRow>
<MDBCol md="4" className="mb-4">
<label> DateofJourney </label>
<input type = "date" value = {this.state.date} onChange={this.handledatechange} /> {/*(onChange = {event => this.setState({date:event.target.value})} required*/}
</MDBCol>
</MDBRow>
<MDBRow>
<MDBCol md="6" className="mb-4">
<MDBInput
label="anything to say"
group
type="text"
validate
error="wrong"
success="right"
value = {this.state.ats} onChange={this.handleatschange}
style={{ maxWidth: "18rem" }}
icon="envelope"
required
/>
</MDBCol>
</MDBRow>
<MDBRow>
<MDBCol md="6" className="mb-4">
<Fragment>
<MDBBtn gradient="blue" type="submit">Submit</MDBBtn>
</Fragment>
</MDBCol>
</MDBRow>
</form>
</MDBContainer>
</div>
);
}
}
export default FindaRide;
Looking at the screenshot you provided, it seems that your Billing Account is based in India.
As you might be aware, Google Maps Platform pay as you go pricing has been launched in India last Nov. 18, 2019. Before this change, your project was subjected to some free limits which may cause OVER_QUERY_LIMIT errors when exceeded.
To fix this issue, you will need to create a new billing account
dedicated for Maps APIs only and migrate your maps projects to this
new account.
Here's a guide that you could follow to learn how to create a new billing account for Maps. Kindly make sure to select the correct business the billing account will pay for (in this case Google Maps Platform).
Below that is also the section that would help you learn how to migrate your projects.
If you still need help with this issue, I would suggest that you file a support case with us on the GCP Console to open a personalized communication channel as this question does not appear to be about programming.
I hope this helps!
I have waited for till 1 30 pm (Indian time) and the quota got refreshed .. And now its working fine.. so the answer is just wait upto "Pacific mid night time" and then start working again peacefully (note that ur billing account should be enabled )

Manage Input inside a List in React

I call a GET from a server and this request return an array of N objects. Then on this array I generate a List using Antd in this way:
render() {
return (
<List
dataSource={this.props.images}
renderItem={image => (
<List.Item actions={
[
<Icon key={"1"+image.Id.toString()} onClick={(e) => this.actionClick('RUN',image.Id, image.RepoTags[0].replace(/[^a-zA-Z0-9]/g,'_'), e)}
className="icon" type="caret-right" />,
<Popconfirm placement="topRight" title="Are you sure delete this image?"
onConfirm={(e) => this.actionClick('REMOVE_IMAGE',image.Id, e)} okText="Yes" cancelText="No">
<Icon key="4" className="icon" type="close" />
</Popconfirm>
]
}>
<List.Item.Meta
title={image.RepoTags[0]}
description={image.Labels ? image.Labels.maintainer : ''}
</List.Item.Meta>
<InputGroup compact className={'inputGroup'}>
<Input style={{ width: '50%' }} placeholder={'inner port'} value={this.state.innerPort} onChange={evt => this.updateValue("innerPort",evt)}/>
<Input style={{ width: '50%' }} placeholder={'redirect'} value={this.state.redirectPort} onChange={evt => this.updateValue("redirectPort",evt)}/>
</InputGroup>
</List.Item>
)}
>
</List>
);
}
As you can see in the code I have an InputGroup for every List.Item and I store the value in the state using:
updateValue(k,v) {
console.log("key", k, "value", v);
console.log(this.state);
this.setState({
[k]:v.target.value
});
}
The problem here is that the I have the same value for every List.Item of the List.
How could I manage this problem with multiple List.Item? I thought of an array, but I didn't make that work.
Change your Input to
<Input style={{ width: '50%' }} placeholder={'inner port'} value={this.state["innerPort"+image.id] } onChange={evt => this.updateValue("innerPort",image.Id,evt)}/>
this will send a unique identifier to the update function and then you can use it like
updateValue(k,id,v) {
console.log("key", k, "value", v);
console.log(this.state);
var myKey=k+id
this.setState({
[myKey]:v.target.value
});
}
Have you tried to use FlatList instead of List, so you can pass the item index to the rendered item.

Resources