OSEMA TOUATI
OSEMA TOUATI

Reputation: 349

can't use replaceAll or replace with nextjs/reactjs

I'm using reactjs/nextjs and I'm currently trying to render this component:

const Example = ({data}) => (
<strong>{() => data.slug.replaceAll("-", " ")}</strong>);

I get this error each time:
TypeError: data.slug.replaceAll is not a function.

The type of slug is a string and i checked it out.
I tried using data.slug.toString().replaceAll... that I've found in another stackoverflow answer but I've got the same issue.

I tried using a function istead of direct string ie.: () => data.slug.replaceAll... and this time there was no rendering.

I don't know if it would help, but the data I try to render comes from an api through getServerSideProps function asynchronously.

Upvotes: 6

Views: 4702

Answers (2)

Nicolas Bouvrette
Nicolas Bouvrette

Reputation: 4767

With the deprecation of Node.js 14, it will now be more common to want to use replaceAll but Chrome only started to support this on version 85 which dates back to August 2020. Breaking your Next.js application, even for older browsers, seems like a bad idea especially considering the low added value of replaceAll. But having the ability to use recent JavaScript functionalities without worrying about compatibility can also be nice. This is where the following fix can come in handy:

  1. Add top-level-await in your Webpack config
config.experiments = { ...config.experiments, topLevelAwait: true }
  1. Install core-js: npm --save-dev i core-js

  2. Add a conditional dynamic import in your _app file that won't increase your base package size:

if (typeof window !== 'undefined' && !String.prototype.replaceAll) {
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  await import('core-js/actual/string/replace-all')
}

This fix can also be used for any non-nextjs-natively-supported polyfills.

Upvotes: 0

k.s.
k.s.

Reputation: 3004

Most likely because .replaceAll() isn't yet supported in all browsers.

caniuse

For the time being, you can use a simple .replace()

data.slug.replace(/-/g, " ")

Upvotes: 13

Related Questions