1

I have this Note element in React to show saved strings input by user from a text area. Somehow, new line is not reflected and replaced by space.

I have checked the strings before it's mapped to paragraph, the string still have the new lines characteres. But when it's mapped to paragraph, the new lines are replaced by spaces.

How to make the new lines remain reflected on the new created paragraph elements? Below is my code.

class Note extends React.Component {

  render() {
    return (
      this.props.notes.map((note, index) => 
        <div className="note-important" key={index}>
          <p>{note}</p>
        </div>
        )

    ); 

  }
}

class NoteAndDone extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      input: '',
      notes: [],
    }

    this.handleClick = this.handleClick.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    this.setState({
      input: e.target.value
    })
  }

  handleClick(e) {
    let input = document.getElementById('textarea-note').value;
    if (input && !/^\s*$/.test(input)) {
      this.setState({
        notes: this.state.notes.concat(this.state.input)
      });
    }
  }

  render() {
    return (
      <div className="NoteAndDone">
        <div className="Title">Note</div>
        <textarea id="textarea-note" onChange={this.handleChange} placeholder='Note important things here...' />
        <div className="button-save-container">
          <button className="btn btn-primary" id="button-save-note" onClick={this.handleClick}>Save</button>
        </div>
        <Note notes={this.state.notes}/>
      </div>
    );
  }
}
Inovramadani
  • 1,955
  • 3
  • 14
  • 34

2 Answers2

0

Perhaps you should replace the newlines with breaks? Simply replace line 7 with:

<p>{note.replace("\n","<br />","g")}</p>

Though there may be a good reason why you chose not to do this...

Caleb H.
  • 1,657
  • 1
  • 10
  • 31
  • Perhaps not. My experience with React has been through React Native, and there you don't even have a `

    ` component. I don't have any way to quickly test this, so I really couldn't say.

    – Caleb H. Aug 10 '18 at 05:01
0

perhaps you could make the following updates to your Note component?

class Note extends React.Component {

  render() {

    return (
        this.props.notes.map((note, index) => 
            <div className="note-important" key={index}>
              { /* split the note string by \n, filter non-empty lines, and map each resulting line to it's own paragraph element */ }
              { note.split('\n').filterline => !!line).map(line => <p> 
              {{ line }}</p>) } 
            </div>
            )

        ); 

      }
     }
Caleb H.
  • 1,657
  • 1
  • 10
  • 31
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65