Skip to content

Only trim nodes if parent can't contain text nodes #384

Closed
@vidhu

Description

@vidhu

When parsing html, in most cases we need to enable trim to prevent the validateDOMNesting errors

domToReact(html, {trim: true})

However this doesn't always work. There may be cases where a div contains a &nbsp character. During parsing, this gets trimmed out.

const html = `
  <div>     Hello</div>
`;

function App() {
  return parse(html, { trim: true });
}

CodeSandBox Demo

Note, the whitespace before the Hello aren't spaces . They are &nbsp.

Would you be open to the idea of allowing users to provide a function for trim that would allow specifying a custom trimmer to handle these special spaces? It would look something like this

const customTrim = node => {
  const data = node.data;
  // some trimming logic
  return data;
}

return parse(html, { trim: customTrim });

I could even see it being extended to check if the node type allows spaces or not and trimming based on that although this can be done in the replacer function also as suggested in #205

const customTrim = node => {
  const {type, name, data} = node;
  if(type === 'tag' && ['div', 'p', ...etc].contains(name)) {
    return data
  }
  return data.trim()
}

I'm happy to create a PR if you're open to this idea

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions