Home > Net >  How to add <br> after new lines fetched from .txt file
How to add <br> after new lines fetched from .txt file

Time:09-20

i have tried to add
using regex that i found on another question but it doesnt work for my case. Im making a notes web program for my class and my goal is to note in seperate .txt files while not manually adding \n after every line

'''

import biology from './notes/biology.txt';
import './App.css';
import React, {useState, useEffect} from 'react';


function App() {
    const [BioText, setBioText] = useState('Failed to fetch text');

    useEffect(() => {
        const getData = async () => {
            const response = await fetch(biology)
                .then(r => r.text())
                .then(BiologyText => {
                    console.log('text decoded:', BiologyText);
                    BiologyText.replaceAll(/(\r\n|\r|\n)/g, '<br>')

                    console.log(BiologyText)
                    return BiologyText
                });
            const data = response.toString();
            setBioText(data);
        };
        getData()
    }, []);

'''

CodePudding user response:

As already mentioned in the comments replaceAll returns you a new string and is not mutating the variable value. This should be done instead:

useEffect(() => {
  const getData = async () => {
    const response = await fetch(biology)
      .then(r => r.text())
      .then(BiologyText => BiologyText.replaceAll(/(\r\n|\r|\n)/g, '<br>'));
           
    setBioText(response);
  };
  getData()
}, []);
  • Related