The Block Editor RichText Component – Single Line Only

React Graphic with a computer
License: Adobe Stock

I was working on an alert block, but I needed something for the title of the alert. I figured I could use the RichText component that comes with Gutenberg (aka, the block editor).

The RichText component allows for returns ( or line breaks). This was problematic, as I only wanted the user to enter one line of text for the headline.

I did a bunch of searching, but it took a nose-dive into the component’s innards to figure out how to do a single line of text.

Enter the prop disableLineBreaks. Just pass it true and you now have a RichText component that is only a single line of text.

Here’s some sample code with the prop set to true.

<RichText
	tagName="h2"
	placeholder={ __( 'Alert title', 'quotes-dlx' ) }
	value={ alert_title }
	className="alertx-dlx-title"
	disableLineBreaks={ true }
	allowedFormats={ [
		'core/bold',
		'core/italic',
		'core/text-color',
		'core/subscript',
		'core/superscript',
		'core/strikethrough',
		'core/link',
	] }
	onChange={ ( value ) => {
		setAttributes( { alert_title: value } );
	} }
	ref={ alertTitleField }
/>Code language: JavaScript (javascript)

Like the tutorial you just read? There's more like it.

There's more where that came from. Enter your email and I'll send you more like it.

This field is for validation purposes and should be left unchanged.

Ask a Question or Leave Feedback

Your email address will not be published. Required fields are marked *