Search code examples
reactjsreact-dom

Creating a function that replace a letter with a line break


I'm trying to create a function that replace some specific character by a line break.

I'm fetching the data from my API but i'm always return [object Object]

my function is write like so:



  const includeFunction = (data) => {
const linebreak = React.createElement('br')
return data.replace("lb182", linebreak)
  }


          <ArticleComponent
            description={includeFunction(job.description)}

};

and i pass it to the render:

 description={includeFunction(job.description)}

any ideas how to replace characters with a linebreak ?


Solution

  • The issue could be in your placing React elements into a string. You could instead have the funtion return an array with the strings and linebreaks. For example:

    function replaceBreaks(data){
        const stringAsArr = data.split("lb182").map(str => [str, <br />]).flat();
        stringAsArr.pop();
        return stringAsArr;
     }