Skip to content

Instantly share code, notes, and snippets.

@Nachasic
Created October 19, 2018 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nachasic/55ba65be46463c70336d700121ec4b6c to your computer and use it in GitHub Desktop.
Save Nachasic/55ba65be46463c70336d700121ec4b6c to your computer and use it in GitHub Desktop.
DraftJS — get decorator's own selection range
/**
* This is a workaround for the following issue:
* https://github.com/facebook/draft-js/issues/1394
**/
type DecoratorProps = {
// draft-js provides decorators with detoratedText property
decoratedText: string;
}
export class Decorator extends React.Component<DecoratorProps, any> {
private GetOwnSelectionRange (): [start: number, end: number] {
// Children of draftjs decorators get their offset as props
const { start } = this.props.children[0].props;
const { decoratedText } = this.props;
return [start, start + decoratedText.length]
}
render () {
return <span>{ this.props.children }</span>
}
}
@Nachasic
Copy link
Author

There is a PR pending that will make draftjs provide range start and end as props to decorators:
facebookarchive/draft-js#1597

Until it is merged and released, one can use this hacky workaround.

@rbecheras
Copy link

Thank you !

Here is a useful snippet for Typescript and react function components users

export type DecoratorProps = {
  start: number
  block: ContentBlock
  isLast: boolean
  offsetKey: string
  selection: SelectionState
}

type DecoratorChild = { props: DecoratorProps }

export const useDecoratorProps = (children: ReactNode): DecoratorProps => {
  const _children = children as DecoratorChild[]
  const child = _children[0]
  return child.props
}

Then in your decorator component, you can grab all using it:

const Decorator: FC<Props> = ({children, ...props}) => {
  const { start, blockstart, isLaststart, offsetKeystart, selectionstart } = useDecoratorProps(children)

  return ...
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment