2

Based off this Q&A:

React wrapper: React does not recognize the `staticContext` prop on a DOM element

The answer is not great for my scenario, I have a lot of props and really dislike copy-pasting with hopes whoever touches the code next updates both.

So, what I think might work is just re-purposing whatever function it is that React uses to check if a property fits to conditionally remove properties before submitting.

Something like this:

import { imaginaryIsDomAttributeFn } from "react"
...

render() {
    const tooManyProps = this.props;
    const justTheRightProps = {} as any;
    Object.keys(tooManyProps).forEach((key) => {
        if (imaginaryIsDomAttributeFn(key) === false) { return; }
        justTheRightProps[key] = tooManyProps[key];
    });
    return <div {...justTheRightProps} />
}

I have found the DOMAttributes and HTMLAttributes in Reacts index.t.ts, and could potentially turn them into a massive array of strings to check the keys against, but... I'd rather have that as a last resort.

So, How does React do the check? And can I reuse their code for it?

Seph Reed
  • 4,704
  • 7
  • 30
  • 65

2 Answers2

1

The following isn't meant to be a complete answer, but something helpful for you in case I forget to come back to this post. The following code is working so far.

// reacts special properties
const SPECIAL_PROPS = [
    "key",
    "children",
    "dangerouslySetInnerHTML",
];

// test if the property exists on a div in either given case, or lower case
// eg (onClick vs onclick)
const testDiv = document.createElement("div");
function isDomElementProp(propName: string) {
    return (propName in testDiv) || (propName.toLowerCase() in testDiv) || SPECIAL_PROPS.includes(propName);
}
Seph Reed
  • 4,704
  • 7
  • 30
  • 65
1

The React internal function to validate property names is located here: https://github.com/facebook/react/blob/master/packages/react-dom/src/shared/ReactDOMUnknownPropertyHook.js

The main thing it checks the properties against is a "possibleStandardNames" property-list here: https://github.com/facebook/react/blob/master/packages/react-dom/src/shared/possibleStandardNames.js

So to reuse their code, you can copy the property-list in possibleStandardNames.js into your project, then use it to filter out properties that aren't listed there.

Venryx
  • 8,962
  • 7
  • 50
  • 61