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
Related
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>
)
}
import React,{useState,useEffect} from 'react';
import { Button, Form } from 'semantic-ui-react';
import axios from 'axios';
import {useNavigate} from 'react-router';
import usePrevious from './prev';
import {Link} from 'react-router-dom';
const Update = () => {
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const [checkbox, setCheckBox] = useState(false);
const [id, setID] = useState(null);
let navigate = useNavigate();
Here I am storing the input field's previous value using another component
to get the previous value
const previous = usePrevious(firstName);
useEffect(() => {
setID(localStorage.getItem('ID'));
setFirstName(localStorage.getItem('First Name'));
setLastName(localStorage.getItem('Last Name'));
setCheckBox(localStorage.getItem('Checkbox Value'))
}, []);
This is where the updated data is being sent to mock api and in if condition i am
comparing previous value with new one(if it changes).
const updateApiData = () => {
axios.put(`https://61cb2af8194ffe0017788c01.mockapi.io/fakeData/${id}`,{
firstName,
lastName,
checkbox
}).then(()=>{
navigate('/read');
})
if(firstName==previous){
console.log("change");
}
}
return(
<div>
<Form>
<Form.Field>
<label>First Name</label>
<input id="i1" placeholder='First Name' value={firstName}
onChange={(e)=>setFirstName(e.target.value)}
/>
</Form.Field>
<Form.Field>
<label>Last Name</label>
<input placeholder='Last Name' value={lastName}
onChange={(e)=>setLastName(e.target.value)} />
</Form.Field>
here on button click i am calling the function of sending data to api.
i need to check here if on click update the field's value is same as the previous one.
<Button type='submit' onClick={updateApiData}>Update</Button>
<Link to="/read">
<Button>Cancel</Button>
</Link>
</Form>
<br></br>
<Button onClick={()=>navigate(-1)}>Go Back</Button>
</div>
)
}
export default Update;
Can someone please explain to me why in this code when I type a character the character that appears in the label tag is different from the character that appears on the console? Is the code correct?
import React, { useState } from "react";
const App = () => {
const [text, settext] = useState("");
const update = (e) => {
settext(e.target.value);
console.log(text);
};
return (
<div>
<input type="text" value={text} onChange={update} />
<label>{text}</label>
</div>
);
};
export default App;
The settext doesn't update the text state instantly. So calling console.log(text) right after it will give interesting results.
What you want to use is useEffect to log out the value of text.
import React, { useState, useEffect } from "react";
const App = () => {
const [text, settext] = useState("");
const update = (e) => {
settext(e.target.value);
};
useEffect(() => console.log(text), [text]);
return (
<div>
<input type="text" value={text} onChange={update} />{" "}
<label> {text} </label>{" "}
</div>
);
};
export default App;
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.
I have a form on 'products/add' and I add products to the database, after I submit the request, I redirect to the page where all the products are displayed. However, this page does not display information about the last item I added. How to fix it? How do I render pages after redirects to display the most current data?
'localhost:3333/products/add'
import React, {useState} from 'react';
import api from './api';
import { Redirect } from 'react-router'
const HandleProduct = () => {
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [redirect, setRedirect] = useState(false);
const updateName = (e) =>{
setName(e.target.value);
}
const updateDescription = (e) =>{
setDescription(e.target.value);
}
const addProduct = (e) =>{
e.preventDefault();
const product = {
name: name,
description: description
}
api.addProduct(product)
.then((req, res) =>{
console.log(res);
setRedirect(true);
})
}
if(redirect) {
return <Redirect to={'/products'} />
}
return (
<div>
<form onSubmit={addProduct}>
<input type="text" name="name" value={name} onChange={updateName}/>
<input type="text" name="description" value={description} onChange={updateDescription}/>
<button>Submit</button>
</form>
</div>
);
}
export default HandleProduct;
List of products(localhost:3333/products):
import React, {useContext} from 'react';
import {ProductsContext} from './ProductsContext';
const ProductsList = () => {
const [data] = useContext(ProductsContext);
return (
<div>
{console.log(data)}
{data.products.map((product, index)=>(
<div key={index}>
<p>{product.name}</p>
<p><i>{product.description}</i></p>
</div>
))}
</div>
);
}
export default ProductsList;