Home > database >  During state change in React, is it possible to append values to URL
During state change in React, is it possible to append values to URL

Time:02-08

I was wondering, if, on state change, I can add something like this to URL

www.abc.com/?state=on

without page reloading.

CodePudding user response:

You can use History.replaceState() in useEffect to change url when state changing

useEffect(() => {
    window.history.replaceState(
        history.state,
        null,
        `?state=${state}`
    );
}, [state]);

CodePudding user response:

You could use the useNavigate hook to navigate to any path you'd want to (This is available from react-router-v6 onwards, if you are using an older version, consider using useHistory). This doesn't cause any page reloads, further using useParams you could also extract the param values to make necessary computations in the target component.

import {useNavigate} from 'react-router-dom'
//OR
import {useHistory} from 'react-router-dom' //Prior to react-router-v6

export default function Component(props){ 
  const navigate = useNavigate()
  //OR
  const history = useHistory()
  
  useEffect(() => {
    history.push({pathname:'/',
     search:'?state=on'
    })
    //OR
    navigate({
     pathname:'/',
     search:'?state=on'},{replace:false}) //Set replace=true if you'd want to disable back navigation, false otherwise.
  }, [state]);

  //REST OF THE COMPONENT LOGIC
  .
  .
  .
}

I suggest you check out the docs of react router for more information.

CodePudding user response:

history.push({
  pathname: '/',
  search: '?state=on'
})

You can use history.push and don't worry about your page reload.

https://v5.reactrouter.com/web/api/history

  •  Tags:  
  • Related