Skip to content

Dynamic children break the component #854

@jonathandewitt-dev

Description

@jonathandewitt-dev

Initial checklist

Affected packages and versions

react-markdown

Link to runnable example

No response

Steps to reproduce

Occasionally, through some whimsical magic, React will choose to render a single string passed to children as an array containing one string. I can't seem to reproduce this scenario reliably, it just happens at what seems like random times.

This being the case, however, means that there are valid markdown strings being passed as children which this component is not resilient enough to handle. I keep getting variations of the error message:

Unexpected value `test` for `children` prop, expected `string`

Where "test" was simply my text string passed as the sole child to the Markdown component. Upon inspection, I was able to discover that my string was being converted to string[] and then rejected by the package. Not a great experience because there's quite literally nothing that can be done within my control when facing this situation.

I was able to fix the problem by temporarily modifying this library's code in my node_modules, from this:

  if (typeof children === 'string') {
    file.value = children
  } else {
    unreachable(
      'Unexpected value `' +
        children +
        '` for `children` prop, expected `string`'
    )
  }

to this:

  const allChildrenAreStrings = Array.isArray(children) ? children.every((child) => typeof child === 'string') : typeof children === 'string';

  if (allChildrenAreStrings) {
    file.value = Array.isArray(children) ? children.join('\n') : children
  } else {
    unreachable(
      'Unexpected value `' +
        children +
        '` for `children` prop, expected `string`'
    )
  }

Expected behavior

It should handle string[] children by confirming that each child is indeed of type string and then Array.join('\n') them to continue processing the markdown.

Actual behavior

For string[] arrays, it reports an error and crashes the app.

Runtime

No response

Package manager

No response

OS

No response

Build and bundle tools

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    👀 no/externalThis makes more sense somewhere else👎 phase/noPost cannot or will not be acted on

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions