Home > Enterprise >  React. Refresh parent component on button click
React. Refresh parent component on button click

Time:06-30

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

CodePudding user response:

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)
            }
          }
        }>
)
}
  • Related