0

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);
    };
2
  • Please provide a better explanation and use 'backticks' to highlight your code blocks Commented Apr 28, 2022 at 8:37
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. Commented Apr 28, 2022 at 16:57

2 Answers 2

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()
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for this, its working, if you could help me with how we can use city in another components pass through event listener?
0

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>
    )
};

1 Comment

Thank you for the feedback, but this does not work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.