Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to align text in Draft.js

I'm wondering how to align text in Draft.js just like on the picture below.

text-align

I have searched this several days, but I haven't found the solution.

like image 364
zhuscat Avatar asked Sep 01 '16 05:09

zhuscat


1 Answers

After reading the source code, I found a way for it. Using blockRenderMap, you can add some custom block types like this:

const blockRenderMap: Record<string, DraftBlockRenderConfig> = {
'header-one-right': {
    element: 'h1',
    wrapper: <StyleHOC style={{ ...blockStylesMap['header-one'], display: 'flex', justifyContent: 'flex-end' }} />,
  },
  'header-two-right': {
    element: 'h2',
    wrapper: <StyleHOC style={{ ...blockStylesMap['header-two'], display: 'flex', justifyContent: 'flex-end' }} />,
  },
  'header-three-right': {
    element: 'h3',
    wrapper: <StyleHOC style={{ ...blockStylesMap['header-three'], display: 'flex', justifyContent: 'flex-end' }} />,
  },
  'unstyled-right': {
    element: 'div',
    wrapper: <StyleHOC style={{ ...blockStylesMap['unstyled'], display: 'flex', justifyContent: 'flex-end' }} />,
  },
};

I use flex to avoid wasting time to find a away to override the internal style .public-DraftStyleDefault-ltr.

StyleHOC is quite simple:

const StyleHOC: React.FC<Props> = ({ style, children }) => {
  const childrenWithStyle = React.Children.map(children, (child) => {
    if (React.isValidElement(child)) {
      return React.cloneElement(child, { style });
    }
    return child;
  });
  
  return <>{childrenWithStyle}</>;
};

And then you can toggle the blockType using RichUtils.toggleBlockType(editorState, blockType).

like image 50
Window0006 Avatar answered Sep 24 '22 01:09

Window0006