React-markdown: Support for declaring size on images

Created on 25 Jan 2019  路  3Comments  路  Source: remarkjs/react-markdown

It would be great if we could get support for the syntax for sizing images that some(ref) markdown renderers support.

![Thumbnail image](foobar.png =50x50)

When there is a space in the url the current parser doesn't seem to treat it as an image at all, so it's not possible to add this via a custom image renderer.

I've used the following (super ugly 馃槀) workaround for now, but would be great if it was supported out of the box 鈽猴笍

import ReactMarkdown from 'react-markdown'

const imageSizeRegex = /_33B2BF251EFD_([0-9]+x|x[0-9]+|[0-9]+x[0-9]+)$/
const imagePreprocessor = (source) => source.replace(/(!\[[^\]]*\]\([^)\s]+) =([0-9]+x|x[0-9]+|[0-9]+x[0-9]+)\)/g, '$1_33B2BF251EFD_$2)')

function imageRenderer ({ src, ...props }) {
  const match = imageSizeRegex.exec(src)

  if (!match) {
    return <img src={src} {...props} />
  }

  const [width, height] = match[1].split('x').map(s => s === '' ? undefined : Number(s))
  return <img src={src.replace(imageSizeRegex, '')} width={width} height={height} {...props} />
}

/**
 * @param {ReactMarkdown.ReactMarkdownProps} props
 */
const Markdown = ({ source, ...props }) => {
  /** @type {ReactMarkdown.ReactMarkdownProps['renderers']} */
  const renderers = {}

  source = imagePreprocessor(source)
  renderers['image'] = imageRenderer

  return <ReactMarkdown source={source} renderers={renderers} {...props} />
}

export default Markdown
馃憖 areexternal 馃檵 typquestion

Most helpful comment

馃憤 Would love to have it too!

All 3 comments

馃憤 Would love to have it too!

This is not a feature of CommonMark, and so would not be added to core.
However it could be added through a remark plugin.
You can find more information on creating plugins at https://unifiedjs.com/learn/

Was this page helpful?
0 / 5 - 0 ratings

Related issues

AlexLerman picture AlexLerman  路  3Comments

kennetpostigo picture kennetpostigo  路  4Comments

dbuchet picture dbuchet  路  3Comments

damianobarbati picture damianobarbati  路  3Comments

wqh17101 picture wqh17101  路  3Comments