skip to Main Content

I am currently creating a next JS application and using react states in that. I want to add a line break in a string value of the state. I tried multiple things like these but none of them work:
setState("a n b");
setState("a <br> b");
setState("a {n} b");
setState("a {'n'} b");
Can someone please help with this

Edit: Sorry for such a vague question. Let me provide a little more context as to what my code currently looks like.

const [ state, setState ] = useState('abc')
const handleSubmit = async (e) =>{
    setState('a');
    if(//some condition){
        setState(state + '<br />b')
    }else{
        setState(state + '<br />c')
    }
}

This is basically how I want my code to be. Any suggestions. Thanks

2

Answers


  1. You need to create a JSX element with <br />, and as string, if you want React to convert it to the correct DOM.

    Use a fragment – <Fragment>{prev state} <br /> b</Fragment>, or the shorthand version (not supported in SO snippets) – <>a <br /> b</>.

    const { useState, Fragment } = React
    
    const Demo = () => {
      const [text, setText] = useState('a')
    
      const add = () => {
        setText(t => <Fragment>{t} <br /> b</Fragment>)
      }
      
      return (
        <div>
          <button onClick={add}>Add</button>
        
          <div>
          {text}
          </div>
        </div>
      )
    }
    
    ReactDOM
      .createRoot(root)
      .render(<Demo />)
    <script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
    
    <div id="root"></div>
    Login or Signup to reply.
  2. I see 2 options here:

    1. is to use the <pre/> to display your text
    import React, { useState } from "react"
    
    export default Demo = _ => {
      const [text, setText] = useState('abc')
      
      return <div>
        <h2>Pre</h2>
        <button onClick={_ => setText(t => `${t}nb` )}>Add</button>
        <pre>{text}</pre>
      </div>
    }
    
    1. use an array and render it’s elements one-by-one
    import { useState } from "react";
    
    export default DemoList = _ => {
      const [text, setText] = useState([ "abc" ]);
    
      return<div>
        <h2>List</h2>
        <button onClick={_ => setText(t => ([ ...t, 'b']))}>Add</button>
        <div>{text.map( (t,ix) => <div key={ix}>{t}</div> )}</div>
      </div>
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search