Home > OS >  How to display response with proper spacing, line-break and formatting in reactjs?
How to display response with proper spacing, line-break and formatting in reactjs?

Time:12-31

I am taking response from OpenAi and store it using React UseState

const [response, setResponse] = useState();

try {
  const res = await axios.post('https://api.openai.com/v1/completions', body, config)
  const completions = res.data.choices[0].text
  console.log(completions)
  setResponse(completions)
  setLoading(false)
} catch (err) {
  console.error(err)
  setLoading(false)
}

when i console the response it appears in this way enter image description here

and when display using this code..

{loading ? (
        <div className='block p-2.5 h-full w-full text-sm text-gray-900 bg-gray-50 rounded-lg border border-gray-300  dark:bg-gray-700 dark:border-gray-600  dark:text-white '>loading...</div>
      ) : (
        <div className="block p-3 h-full w-full text-sm text-gray-900 bg-gray-50 rounded-lg border border-gray-300  dark:bg-gray-700 dark:border-gray-600  dark:text-white " >
          {response}
        </div>
      )}

it will appears like this: enter image description here

CodePudding user response:

An div element does not parse spaces or carriage return. As a solution for your problem I recommend to use <pre> tag or to use css property white-space (white-space: pre;)

  • Related