Last active
June 20, 2020 20:51
-
-
Save gauravsoti1/e142070aa24105df1316a3498a926503 to your computer and use it in GitHub Desktop.
A function to find DraftJS Entity
This file contains 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
export const getEntitiesByLogic = ({ editorState, findEntity }) => { | |
const content = editorState.getCurrentContent(); | |
const entities = []; | |
content.getBlocksAsArray().forEach(block => { | |
let selectedEntity = null; | |
block.findEntityRanges( | |
character => { | |
if (character.getEntity() !== null) { | |
const entityKey = character.getEntity(); | |
const entity = content.getEntity(entityKey); | |
const entityData = entity.getData(); | |
const entityType = entity.getType(); | |
// If our logic is successful | |
if ( | |
findEntity({ type: entityType, data: entityData }) | |
) { | |
// set data | |
selectedEntity = { | |
entityKey, | |
blockKey: block.getKey(), | |
entity: content.getEntity(character.getEntity()) | |
}; | |
return true; | |
} | |
} | |
return false; | |
}, | |
(start, end) => { | |
// We are using this function because in most of the scenarios when using entity, | |
// we need start and end position of the entity as well which we only get here | |
entities.push({ ...selectedEntity, start, end }); | |
} | |
); | |
}); | |
return entities; | |
}; | |
const findEntity = ({ type, data }) => { | |
return type === 'mention' && entityData.id === 1; | |
} | |
//We use the above function like this: | |
const entities = findEntitiesByLogic({editorState, findEntity}); | |
//Result that we get: | |
const results = [{ | |
entityKey: "myEntityKey", | |
blockKey: "myBlockKey", | |
entity: EntityObject, | |
start: 4, | |
end: 10 | |
}] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment