'I get an error undefined reading push in React
This is my code. I'm having an error undefined reading push. I want to pass City to another component.
const onInputCityChangeHandler = (e) => {
setCity(e.target.value);
};
const submitForm = (e) => {
e.preventDefault();
props.history.push({pathname: "/",city,});
console.log(city);
};
Solution 1:[1]
I am assuming that you using functional based components. So there is no need to pass history in props. Instead of this use this hook:
const history = useHistory()
If you are using react-router-dom v6 then,
const history = useNavigate()
Solution 2:[2]
Try with this way
const COMPONENT1 = () => {
const history = useHistory();
const [city, setCity] = React.useState(null);
const onInputCityChangeHandler = (e) => {
setCity(e.target.value);
};
const submitForm = () => {
history.push({
pathname: city,
});
};
return (
<form>COMPONENT1</form>
)
};
const COMPONENT2 = () => {
const history = useHistory();
useEffect(() => {
console.log(history.pathname)
})
return (
<div>COMPONENT2</div>
)
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | RoshaanAli |
Solution 2 | Hakob Sargsyan |