skip to Main Content

For some reason in my react app, the following code triggers a compilation error in Webpack using the typescript loader (ts-loader):

handleEdit(): void {
    window.location.href = `/edit/${this.props.entry.id}`;
}

TS2540: Cannot assign to ‘href’ because it is a read-only property.

I suspect it’s some kind of odd artifact of my environment. I have this environment:

"react": "^17.0.1"
webpack: 5.61.0
webpack-cli: 4.9.1
webpack-dev-server 4.11.1
"ts-loader": "^9.2.6",
"typescript": "^4.4.4",

2

Answers


  1. Chosen as BEST ANSWER

    I never figured out the answer. My workaround was using react-dom-router and changing all instances of window.location.href = ... to reload(...), which solved the problem.


  2. use window.location.assign. from here

    window.location.assign Property:

    • The assign function is similar to the href property as it is also used to navigate to a new URL.
    • The assign method, however, does not show the current location, it is only used to go to a new location.
    • Unlike the replace method, the assign method adds a new record to history (so that when the user clicks the “Back” button, he/she can
      return to the current page).
    • However, rather than updating the href property, calling a function is considered safer and more readable.
    • The assign() method is also preferred over href as it allows the user to mock the function and check the URL input parameters while
      testing.
    window.location.assign(`/edit/${this.props.entry.id}`)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search