Home > Enterprise >  How do I read a \n in a string variable typescript
How do I read a \n in a string variable typescript

Time:03-13

There are data from Realtime Data base that has \n between the text to represent a new paragraph, however, when taking it from DB and putting in a String variable, the website doesn't recognize the \n as a new paragraph:

enter image description here

Here is my code:

type EventType = {
    id: string,
    autorID: string,
    autorNome: string,
    titulo: string,
    categoria: string,
    dateS: string,
    dateE: string,
    descricao: string,
    cancelado: string
}

export function useEvent(eventID: string){

    const [ evento, setEvento ] = useState<EventType>()

    useEffect(()=>{
        const eventRef = database.ref(`eventos/${eventID}`)

        eventRef.once('value', evento =>{
            //console.log(evento.val());
            const eventValue = evento.val();

            const vari:EventType = {
                id: eventValue.key,
                autorID: eventValue.authorID,
                autorNome: eventValue.authorName,
                titulo: eventValue.title,
                categoria: eventValue.category,
                dateS: eventValue.startDate,
                dateE: eventValue.endDate,
                descricao: eventValue.description,
                cancelado: eventValue.canceled
            }

            setEvento(vari)
            
        })
    },[eventID]) 

    return{evento}
}

And here is how it shows in HTML: enter image description here

CodePudding user response:

try this

import { useState, useEffect } from 'react'

export default function App() {
  const [text, setText] = useState('write description /n this ')
  useEffect(()=> {
    setText(text.replace('/n', "<br />"))
  },[])
  return (
    <div className="App">
      <div dangerouslySetInnerHTML={{ __html: text }} /> 
    </div>
  );
}

CodePudding user response:

No need to dangeriously set html:

export default function App(props) {
  return (
    <div className="App">
      {props.text.split("\n").map(line=><div>{line}</div>}
    </div>
  );
}
  • Related