0

In my react component, I'm using the replace method to replace a word however this doesn't appear to be working:

const myComponent = () => {

   const [textVal, setTextVal] = useState("hello there")

   textVal.replace("hello", "hi")

   console.log(textVal) // expecting "hi there" but still getting "hello there"

   return ( ... )

}
Eric Nguyen
  • 926
  • 3
  • 15
  • 37
  • 2 things: first, [`replace`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) returns a new string, it doesn't modify the old. Second, if you want this to persist between renders, you would need to call `setTextVal` with the new value. – zero298 Aug 16 '21 at 16:44
  • Does this answer your question? [JS replace not working on string](https://stackoverflow.com/questions/12231644/js-replace-not-working-on-string) – zero298 Aug 16 '21 at 16:44

1 Answers1

1

In react state is immutable, you cant change the value of a state by simply assigning a value to it, you need to use the provided setter function for it:

const myComponent = () => {

   const [textVal, setTextVal] = useState("hello there")

   setTextVal(val=> val.replace("hello", "hi"))

   console.log(textVal) 

   return ( ... )

}

Abd Elbeltaji
  • 473
  • 2
  • 13