0

How to reload/refresh a parent component on button click.

In the code below i refresh page with javascript vanilla (window.location.reload(false)

Is there a way to reload the parent component or page without refreshing the page?

return product ? (
    <div>
      <div>
        <img src={product.images[0]} alt={product.title} />
      </div>
      <div>
        {product.title}
        <br />
        ${product.price}
        <br />
        {product.description}
      </div>
      <div>
        <button onClick={
          () => { 
            setLiked(!liked)
            if (favProduct) {
              window.location.reload(false)
            }
          }
        }>
          <Icon size="28px" />
        </button>
      </div>
    </div> 
  ) : <p>Loading Product... </p>;
2
  • You are refreshing whole page from Child component to re-render Parent component? Commented Jun 29, 2022 at 14:27
  • Yes, asking if there is a way to re-render Parent component without refreshing whole page Commented Jun 29, 2022 at 14:30

1 Answer 1

1

Not sure why you would want to do something like that, but here is one way to do it:

const Parent = () => {
const [toggleRefresh, setToggleRefresh] = useState(false)


return (
<Child setToggleRefresh={setToggleRefresh}/>
)
}


const Child = (props) => {

return (
   <button onClick={
          () => { 
            setLiked(!liked)
            if (favProduct) {
              //this will toggle the state of the parent, forcing a parent rerender
              props.setToggleRefresh(prev => !prev)
            }
          }
        }>
)
}
Sign up to request clarification or add additional context in comments.

Comments

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.