wong1
wong1

Reputation: 59

Line breaks in textareas in React

I'm trying to set the value of a textarea based on an existing array but I want the array items to be separated by a new line on the textarea. I want the textarea to have the items on the unordered list so that I can make a button that can copy the textarea's content into the clipboard.

I get this error: Expecting Unicode escape sequence \uXXXX I think because of the \n. I really don't know what else to do. Thanks in advance for your help.

class NamesList extends Component{
	constructor(props){
		super(props);

	}

	render(){
		const RenderedNames = this.props.formattedNames.map((name, index) => {
			return <li key={index} >{name}</li>
		});

		const formattedNamesBreak = this.props.formattedNames.map((name, index) => {
			return name \n
		});

		return(
			<div>
			<ul className='media-list list-group'>
				{RenderedNames}
			</ul>
			<textarea className='hidden' readOnly='true' value={formattedNamesBreak}></textarea>
			</div>
		);
	}
	
};


export default NamesList;

Upvotes: 2

Views: 3301

Answers (1)

MrCode
MrCode

Reputation: 64526

As your array is an array of strings (the names), you don't need to map() because that would create a resulting array and if you try to output an array as the textarea value, it will be converted to a string with commas to separate the values.

The solution is to call Array.prototype.join() on the array and use a new line as the "glue":

var formattedNamesBreak = this.props.formattedNames.join('\n');

Upvotes: 3

Related Questions