reactjs material ui button not worked - reactjs

I was trying to make a simple react weather app and it worked but not properly because before add the material-ui button it was working perfect and now it is working only if i click enter not click on the button because the material-ui const city = e.target.elements.city.value; this code is not working with it at all
here is the form component is like
return (
<div>
<form onSubmit={props.getWeather}>
<p>Just type the city name </p>
<p className="check">you must spelling correctly</p>
<TextField
id="standard-basic"
name="city"
placeholder="City....."
variant="outlined"
/>
<Button onClick={props.getWeather} variant="contained" color="primary">
find
</Button>
</form>
</div>
);
};
export default Form;
and in the app component
getWeather = async e => {
e.preventDefault();
const city = e.target.elements.city.value;
const api = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${API_KEY}`
);
const data = await api.json();

Remove onClick handler from button and add type="submit", so it'll work both in case of Enter click and button click:
<Button type="submit" variant="contained" color="primary">
find
</Button>
It's going to work only when your button is in hierarchy of <form> type="submit" simply submits the form.

Related

React set multiple states on an event

I have a modal that when it is closed updates a state. The modal also has a div which will be replaced if a button is clicked. The button is replaced with a text area and 2 buttons (one of them a cancel.) If the cancel is clicked, the state updates and the text area hides. All good. However, if the user closes the modal, then the state is not updated and the div is shown next time.
I am unsure of how to set 2 states on close for the modal, I think this could sort this issue.
Code has been updated as per #jsNoob suggestion:
Hint component has
const [showModalProblemS_vid, setShowModalProblemS_vid] = useState(false);
<VideoModal showModal={showModalProblemS_vid} closeHandler={() => setShowModalProblemS_vid(false)} videoMessage={props.prob_s_vid} size='med'/>
So how to set a state which is not in the file is the issue
Modal Code below:
import Button from 'react-bootstrap/Button';
import Modal from 'react-bootstrap/Modal';
import { useState } from 'react';
function VideoModal({showModal = false, closeHandler = () =>{}, videoMessage, content, size}) {
const [confused, setConfused] = useState(false)
return (
<Modal
size={size}
show={showModal}
onHide={closeHandler}
onClose={()=> {setConfused(false); closeHandler()}}
backdrop="static"
keyboard={false}
>
<Modal.Body>
<video src={videoMessage} controls autoPlay></video>
<div>
{confused ? (
<div>
What have you found confusing about this video?
<textarea className='confusedText' rows="2"></textarea>
<Button className="confusedBtnSave">
Save
</Button>
<Button className="confusedBtnCancel" onClick={()=>setConfused(false)}>
Cancel
</Button>
</div>
) : (
<div>
<Button className="confusedBtn" onClick={()=>setConfused(true)}>
Confused?
</Button>
</div>
)}
</div>
</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={closeHandler}>
Close
</Button>
</Modal.Footer>
</Modal>
)
}
export default VideoModal
Well to set multiple states you can do that inline
<Button onClick={() => {setState1(foo); setState2(bar)}}></Button
Or you could add them to a function and then call the function inline
function multipleStates(foo, bar){
setState1(foo)
setState2(bar)
}
<Button onClick={() => multipleState(foo, bar)}></Button>
I'm not sure if that is too broad of an answer for you, hopefully I haven't misinterpreted your question.
Got this working. I had to use the following:
onClick={() => {onClose(); setConfused(false)}}
note the semi-colon between the states

How to disable arrow keys in google autocomplete address search dropdown - React Js

I have integrated google autocomplete in my React Js project(screenshot attached), when a user enters something in textbox it shows autocomplete address in dropdown. I want to allow user to click on any particular address using mouse only and thus disable arrow keys navigation.
Here is my code on react js
const SearchPanel = () => {
const [state, updateState] = useState(SearchPanelState);
useEffect(() => {
var placeData = new google.maps.places.Autocomplete(document.getElementById('searchLocation'));
google.maps.event.addListener(placeData, 'place_changed', function () {
const googleResponse = placeData.getPlace();
updateState({...state, types: googleResponse.types, placeId : googleResponse.place_id});
});
});
return (
<Fragment>
<div className="search_panel clearfix">
<div className="form-group">
<input type="text" className="form-control" placeholder="Enter Address... " id="searchLocation"/>
</div>
<button className="btn btn-primary ripple" type="button" style={{background:'#ff3366'}}
onClick={() => functionToRedirect(state, updateState)}>Search
</button>
</div>
</Fragment>
)
You can check what you receive in event object and each key on keyboard is associated with character code identify that code and compare with one you receive in event object and then simply return so handler won’t do anything giving you a feel keys are disabled

Submit Final Form from modal

I have issue with my final form. I have a Modal with a react-final-form in it and would like to submit the form with the button which is in the footer of the modal. Submit button has onSubmit event, when I clicked this button I saw that my onSubmit function doesn't work. It works when I click button which opens modal.... What is going wrong here?
Advert.js
class Advert extends React.Component {
showLoginMenu = (e) => {
e.preventDefault();
this.props.loadModal(LOGIN_MODAL);
};
....
<button onClick={this.showLoginMenu.bind(this)}>Order</button>
}
Modal.js
<Modal onClose={this.onClose.bind(this)}>
<Form
onSubmit={this.onSubmit}
initialValues={initValues}
decorators={[calculator]}
render={({handleSubmit}) => (
<form onSubmit={handleSubmit}>
<some fields>
<button type="submit" onSubmit=
{this.onSubmit}>Order</button>
</form>
)}
/>
As far as I know, onSubmit is a prop of form tag, not button tag. You should use onClick instead.
I know this has probably been resolved by now as this issue is about 2 years old.
But to resolve this issue you need to include the Modal inside of the Form component, but before the form tag
<Form
onSubmit={this.onSubmit}
initialValues={initValues}
decorators={[calculator]}
render={({handleSubmit}) => (
<Modal onClose={this.onClose.bind(this)}>
<form onSubmit={handleSubmit}>
<button type="submit" onSubmit={this.onSubmit}>Order</button>
</form>
<Modal>
)}
/>

React Forms and Events

I have a search form with a few inputs the user can enter data into and some buttons on the right hand side that toggle the search. Underneath everything is the main 'search' button. What happens when the user hits return or enter in any of the inputs is on of my toggle buttons onClick handlers always fires and I don't know why. I recreated the gist of this in fiddle/code here:
class Sample extends React.Component {
handleSubmit(e) {
e.preventDefault();
console.log('handle search called');
}
handleClick(e) {
e.preventDefault();
console.log('handleClick called');
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<div className="filterRow">
<div className="filterColumn1">
<label style={{"display":"block"}}>
Name:
<input type="text" name="name" />
</label>
<label>
Id:
<input type="text" name="id" />
</label>
</div>
<div className="filterColumn2">
<button key="sth" onClick={this.handleClick}>
do something
</button>
</div>
</div>
<button type="submit" onClick={this.handleSubmit}>
SEARCH
</button>
</form>
);
}
}
ReactDOM.render(<Sample/>, document.getElementById('app'))
JSFiddle
Question: Why does the click handler on that button fire when you hit enter or return in the inputs? How come its not the handleSubmit which is the onsubmit of the form?
When you hit Enter this triggers your button with submit type (that's just natural behavior of forms not sure why). Your button onClick handler (handleClick) has e.preventDefault() called which prevents further bubbling of an event and that's why handleSubmit is not getting triggered.
If you change button type to type="button" then Enter will not trigger your button onClick handler.
Btw. on your example onSubmit has handleSearch as event handler but I guess you meant handleSubmit.

How to force Enter key to trigger "submit" function without need to focus an input

I'm making an app in react-redux and I want a simple feature but that's starting to look tricky to implement.
:)
I want to be able to open my webapp (I land on my login screen) and just hit enter (the browser has already saved my user and password and they are filled in in the correct input fields) and have that "enter" keystroke tigger my login function without me needing to click anywhere first to focus something.
(On a non-root component)
I've already got my password input (the last one) bound to the enter key correctly.
So pressing enter when I have the password field focused works :
handleSubmit() {
const { authenticate } = this.props;
const { tusername, tpassword } = this.state;
const credentials = {
username: tusername,
password: tpassword,
};
authenticate(credentials);
}
_handleKeyPress = (e) => {
if (e.key === 'Enter') {
this.handleSubmit();
}
};
render() {
return (
<div onKeyPress={this._handleKeyPress} >
<Card id="signin">
<CardImg top width="100%" src={rubisLogo} alt="Rubis" />
<InputGroup>
<Input
placeholder="Nom d'utilisateur"
value={this.state.tusername}
onChange={this.updateUser}
/>
</InputGroup>
<InputGroup>
<Input
placeholder="Mot de passe"
type="password"
value={this.state.tpassword}
onChange={this.updatePassword}
onKeyPress={this._handleKeyPress}
/>
</InputGroup>
<div>
<Button
id="btn"
onClick={this.handleSubmit}
to="/home">Login
</Button>
</div>
<ModalPassword class="modal" buttonLabel="Mot de passe oublié ?" />
<ModalAccount class="modal" buttonLabel="Créer un compte" />
</Card>
</div>);
}
as you can see I've tried putting it on the div but that didn't work. also I don't want a solution based on that. I want the enter-key to be a gobal fallback on this view. the user can't loose this funtionality just because he clicked somewhere.
Set the focus to the div by default using tabIndex so that the javascript event will be triggered
render() {
return (
<div onKeyPress={this._handleKeyPress} tabIndex="1" >
<Card id="signin">
..)}
You have to wrap your components with a form tag instead of a div, handle the onSubmit event, and the property type of Login button you must set it to submit.
...
handleSubmit = (e) => {
e.preventDefault(); // prevent browser behavior
// Handle submit logic
...
};
render() {
return (
<form onSubmit={handleSubmit}>
...
<Button
id="btn"
type="submit"
to="/home">Login
</Button>
</form>
);
}

Resources