Created
October 19, 2018 13:54
-
-
Save Nachasic/55ba65be46463c70336d700121ec4b6c to your computer and use it in GitHub Desktop.
DraftJS — get decorator's own selection range
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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> | |
} | |
} |
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
There is a PR pending that will make draftjs provide range
start
andend
as props to decorators:facebookarchive/draft-js#1597
Until it is merged and released, one can use this hacky workaround.