SwitchUp SwitchUp Ranked Best Coding Bootcamps 2025

How to solve Draft.js convertFromHTML converting image <img> tags into 'unstyled' contentBlock type instead of 'atomic' content block type?

Altcademy Team wrote on 7 February 2018

I solved this by iterating through the contentBlocks generated by convertFromHTML and checking if it has an entity type of image then editing the contentBlock type to 'atomic' like this:
export const CustomContentStateConverter = (contentState) => { // changes block type of images to 'atomic' const newBlockMap = contentState.getBlockMap().map((block) => { const entityKey = block.getEntityAt(0); if (entityKey !== null) { const entityBlock = contentState.getEntity(entityKey); const entityType = entityBlock.getType(); switch (entityType) { case 'IMAGE': { const newBlock = block.merge({ type: 'atomic', text: 'img', }); return newBlock; } default: return block; } } return block; }); const newContentState = contentState.set('blockMap', newBlockMap); return newContentState; };

Trusted by

Students and instructors from world-class organizations

Imperial College London
Carnegie Mellon University
City University of Hong Kong
Hack Reactor
Cisco Meraki
University of Oxford
Swift
Bazaarvoice
Waterloo
Uber
AtlanTech
Tumblr
Boston College
Bombardier Aerospace
University of St. Andrews
New York University
Minerva Schools at KGI
Merrill Lynch
Riot Games
JP Morgan
Morgan Stanley
Advanced Placement®
Google
KPMG
The University of Hong Kong
University of Toronto
SCMP
Moat
Zynga
Hello Toby
Deloitte
Goldman Sachs
Yahoo
HSBC
General Assembly
Tesla
McGill University
Microsoft

Join the upcoming Cohort #97

Enroll for January 6th, 2025