I have a search bar and I want the user to be able to call the handleSearch function when they click the search button or hit the enter key. The search button works fine but I can't for the life of me get it to work when the enter key is hit. Help, please :)
import React, { useState } from 'react';
import { Form, FormControl, Button } from 'react-bootstrap';
import { useHistory } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { searchBlogs, setSearchQuery } from '../../actions/searchBlogsAction';
function SearchComponent() {
const history = useHistory();
const dispatch = useDispatch();
const [searchInput, setSearchInput] = useState('');
const inputHandler = (e) => {
setSearchInput(e.target.value);
};
// Search blogs and redirect to the search results page
const handleSearch = (e) => {
if (e.keyCode === 13 || e == ??) {
e.preventDefault();
history.push('/search-results');
dispatch(setSearchQuery(searchInput));
dispatch(searchBlogs(searchInput));
setSearchInput('');
}
};
return (
<Form inline>
<FormControl
type="text"
size="sm"
placeholder="Search"
className="mr-sm-2"
onChange={inputHandler}
value={searchInput}
onKeyPress={handleSearch}
/>
<Button size="sm" variant="outline-secondary" onClick={handleSearch}>
Search
</Button>
</Form>
);
}
export default SearchComponent;
Try this:
<FormControl
type="text"
size="sm"
placeholder="Search"
className="mr-sm-2"
onChange={inputHandler}
value={searchInput}
onKeyPress={event => event.key === "Enter" && handleSearch()}
/>
And the handleSearch function should just be:
const handleSearch = (e) => {
e.preventDefault();
history.push('/search-results');
dispatch(setSearchQuery(searchInput));
dispatch(searchBlogs(searchInput));
setSearchInput('');
}
According to react-bootstrap docs regarding Form, you can pass onSubmit callback to the Form component, like so:
- <Form inline>
+ <Form inline onSubmit={handleSearch}>
You want to add an onSubmit event handler to the form instead.
import React, { useState } from 'react';
import { Form, FormControl, Button } from 'react-bootstrap';
import { useHistory } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { searchBlogs, setSearchQuery } from '../../actions/searchBlogsAction';
function SearchComponent() {
const history = useHistory();
const dispatch = useDispatch();
const [searchInput, setSearchInput] = useState('');
const inputHandler = (e) => {
setSearchInput(e.target.value);
};
// Search blogs and redirect to the search results page
const handleSearch = (e) => {
e.preventDefault();
history.push('/search-results');
dispatch(setSearchQuery(searchInput));
dispatch(searchBlogs(searchInput));
setSearchInput('');
};
return (
<Form inline onSubmit={handleSearch}>
<FormControl
type="text"
size="sm"
placeholder="Search"
className="mr-sm-2"
onChange={inputHandler}
value={searchInput}
/>
<Button type="submit" size="sm" variant="outline-secondary">
Search
</Button>
</Form>
);
}
export default SearchComponent;
Clicking the submit button in a form will trigger the submit event as will hitting the enter key.
Related
I am giving city name(ex: Chicago) in the Input box and Clicking on the submit button , now I am getting some Response from API, Now I Need to populate the Whole placename field from API into Input box when I click on that Submit Button (Ex : It should be like "Chicago, Illinois, United States" into the Input box)... How can I Populate the Whole Address into the InputBox from API?
Can anyone help me in this?
Here is my Component
import React, { useState } from 'react'
import { useDispatch, useSelector } from 'react-redux';
import * as getallcoordiantes from '../../src/Redux/googlemaps/bigbasket.actions';
const GetGeoCoordinates = () => {
const [storeDetails, setstoreDetails] = useState({
name: ""
})
const dispatch = useDispatch();
const storeInfo = useSelector((state) => state.fetchAllData)
//console.log(storeInfo)
const hanldeChange = (e) => {
let newStoreDetails = { ...storeDetails };
newStoreDetails[e.target.name] = e.target.value;
// console.log(newStoreDetails);
setstoreDetails(newStoreDetails)
}
const getStoreDetails = () => {
dispatch(getallcoordiantes.fetchcoordinates(storeDetails.name))
}
return (
<div>
<h2>Search For Store</h2>
<form>
<input type="text" name="name" value={storeDetails.name} onChange={(e) => { hanldeChange(e) }} />
<button onClick={getStoreDetails} type="button">Get Location</button>
</form>
</div>
)
}
export default GetGeoCoordinates
import "./App.css";
import { useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { addUser} from "./features/Users";
function App() {
const dispatch = useDispatch();
const userList = useSelector((state) => state.users.value);
const [name, setName] = useState("");
const [username, setUsername] = useState("");
return (
<div className="App">
{" "}
<div className="addUser">
<input
type="text"
placeholder="Name..."
onChange={(event) => {
setName(event.target.value);
}}
/>
<input
type="text"
placeholder="Username..."
onChange={(event) => {
setUsername(event.target.value);
}}
/>
<button
onClick={() => {
dispatch(
addUser({
id: userList[userList.length - 1].id + 1,
name,
username,
})
);
}}
>
{" "}
Add User
</button>
</div>
);}
I am new to react and redux. After clicking the "Add User" button, new User data from inputs in the code will be added to the backend list. I want the values in input sections to be cleared after clicking the "Add User" button, but I don't know how to do.
you need to clear your state after click on submit button. for ex: set function like =>
const clearData = {
setName("")
setUsername("")
}
and pass the func to your onClick event.
onClick={clearData}
The following code will work perfectly fine.
Just assign value={name} and value={username} to both input types respectively and when you click Add User just clear the data in both the states.
import "./App.css";
import { useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { addUser} from "./features/Users";
function App() {
const dispatch = useDispatch();
const userList = useSelector((state) => state.users.value);
const [name, setName] = useState("");
const [username, setUsername] = useState("");
return (
<div className="App">
{" "}
<div className="addUser">
<input
type="text"
placeholder="Name..."
value={name}
onChange={(event) => {
setName(event.target.value);
}}
/>
<input
type="text"
placeholder="Username..."
value={username}
onChange={(event) => {
setUsername(event.target.value);
}}
/>
<button
onClick={() => {
setName("");
setUsername("");
dispatch(
addUser({
id: userList[userList.length - 1].id + 1,
name,
username,
})
);
}}
>
{" "}
Add User
</button>
</div>
);}
You can maintain a simple variable with list of form fields and can update the form state with the variable when you needed to clear form data. The below approach comes handy when you need to add additional fields as well.
import "./App.css";
import { useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { addUser} from "./features/Users";
const formFields = { name: '', username: '' };
function App() {
const dispatch = useDispatch();
const userList = useSelector((state) => state.users.value);
const [params, setParams] = useState(formFields)
const handleChange = (e) => {
const { name, value } = e.target;
setParams({ ...params }, ...{[name]: value});
}
const clearForm = () => setParams(formFields);
return (
<div className="App">
<div className="addUser">
<input
type="text"
placeholder="Name..."
value={params.name}
onChange={(e) => handleChange(e)}
/>
<input
type="text"
placeholder="Username..."
value={params.username}
onChange={(e) => handleChange(e)}
/>
<button
onClick={() => {
dispatch(
addUser({
id: userList[userList.length - 1].id + 1,
...params
})
);
clearForm();
}}
>
{" "}
Add User
</button>
</div>
</div>
)
}
I cannot click on my input text box or button at all anymore for some reason. It broke as I was styling the elements. When i first load the page, the autofocus attribute still works but as soon as I try to click the button or re-enter the text box it doesn't work.
import React, { useState } from 'react';
import axios from 'axios';
function Header() {
const [text, setText] = useState("");
function handleChange(event) {
setText(event.target.value);
}
function handleClick() {
const geoCoderURL = "http://api.openweathermap.org/geo/1.0/direct?q=" + text + "&limit=5&appid=feab629ddad64dc21d6412ebae467d79"
function getCoordinates(url) {
axios.get(url).then((response) => {
const locationLat = response.data[0].lat;
const locationLon = response.data[0].lon;
console.log(locationLat, locationLon);
});
}
getCoordinates(geoCoderURL);
}
return (
<div className="header">
<h1 className="headerTitle">Five Day Forecast</h1>
<input onChange={handleChange} type="text" name="name" autoFocus placeholder="Enter city name here."/>
<button type="submit" onClick={handleClick}>Forecast</button>
</div>
)
}
export default Header;
Check this. Here is the Sandbox Link
import React, { useState } from "react";
import axios from "axios";
function Header() {
const [text, setText] = useState("");
const [locationLat, setlocationLat] = useState("");
const [locationLon, setlocationLon] = useState("");
function handleClick() {
console.log(text);
axios.get(
`https://api.openweathermap.org/geo/1.0/direct?q=${text}&limit=5&appid=feab629ddad64dc21d6412ebae467d79`
)
.then(function (response) {
setlocationLat(response.data[0].lat);
setlocationLon(response.data[0].lon);
})
.catch(function (error) {
console.log(error);
});
}
function handleInput(e) {
setText(e.target.value);
}
return (
<div className="header">
<h1 className="headerTitle">Five Day Forecast</h1>
<input
onChange={handleInput}
type="text"
name="name"
autoFocus
placeholder="Enter city name here."
/>
<button onClick={handleClick}>Forecast</button>
<p>{locationLat}</p>
<p>{locationLon}</p>
</div>
);
}
export default Header;
Revoke the API Key or APP ID, Don't post it publically
I'm trying to take input and then display it once the form is submitted but it is not being displayed.
I first use a hook to get the text inside the input field. Once the button is pressed I run a function that uses another hook and sets its value to the text in the input field. This is then put inside the render.
The problem I'm having is that as soon as I submit the form, the screen goes blank.
I have attached my code below.
import React from "react";
import { useState } from "react";
const App = () => {
const [Text, setText] = useState('');
const [Input, setInput] = useState('');
const showInp = (e) => {
e.preventDefault();
setInput(Text);
};
return(
<div className="Main">
<p>
The following cryptocurrencies are available: Bitcoin(BTC).
</p>
<form onSubmit={showInp}>
<label htmlFor="CurrencyName">Currency Name: </label>
<input type="text" className="CurrencyName" value={Text} onChange={(e) => setText(e.target.value)} />
<button style={{marginLeft:"5px"}} type="submit">Submit</button>
</form>
{Input !== '' &&(
{Input}
)}
</div>
)
}
export default App;
Any help would be appreciated.
You have syntax error while rendering Input value. instead of Input value you are rending an object which has Input key and its values is Input, and react can not render objects, it will throw an error.
import React from 'react';
import { useState } from 'react';
const App = () => {
const [Text, setText] = useState('');
const [Input, setInput] = useState('');
const showInp = e => {
e.preventDefault();
setInput(Text);
};
return (
<div className="Main">
<p>The following cryptocurrencies are available: Bitcoin(BTC).</p>
<form onSubmit={showInp}>
<label htmlFor="CurrencyName">Currency Name: </label>
<input
type="text"
className="CurrencyName"
value={Text}
onChange={e => setText(e.target.value)}
/>
<button style={{ marginLeft: '5px' }} type="submit">
Submit
</button>
</form>
{/* Below line had error */}
{Input !== '' && Input}
</div>
);
};
export default App;
This is the example of Textarea where i could not able to set the state value in form-control,..
i could not able to save the state value ,
<Form.Group controlId="exampleForm.ControlTextarea1">
<Form.Control className="textarea"
value={selectDesc}
as="textarea"
rows={7}
onChange={(event)=>setSelectDesc(event.target.value)}>
</Form.Control> </Form.Group>
outout of the screen ,..
This is an example on how you could achieve this (I used an <input> tag but this would have the same result for a <Form /> from react-bootstrap):
import { useState } from "react"; // import useState
export default function App() {
const [name, setName] = useState(""); // useState hook
// handle change event
const handleChange = (e) => {
e.preventDefault(); // prevent the default action
setName(e.target.value); // set name to e.target.value (event)
};
// render
return (
<div>
<input value={name} type="text" onChange={handleChange}></input>
<p>{name}</p>
</div>
);
}
I made a handler function to make the code a bit cleaner, don't forget to prevent the default action and set the value.
This would be the result using react-bootstrap
import { useState } from "react"; // import useState
import { Form } from "react-bootstrap";
export default function App() {
const [name, setName] = useState(""); // useState hook
// handle change event
const handleChange = (e) => {
e.preventDefault(); // prevent the default action
setName(e.target.value); // set name to e.target.value (event)
};
// render
return (
<div>
<Form>
<Form.Group>
<Form.Control
value={name}
type="text"
onChange={handleChange}
></Form.Control>
</Form.Group>
</Form>
<p>{name}</p>
</div>
);
}
Check out my sandbox here