Is it possible to create non-existing properties in child components in React?

41 Views Asked by At

I need to define some properties dynamically in child components of a tree (which do not support such properties), for the purpose of applying e2e tests, but I don't know if this is possible and how to do it in react

Example

We define our components normally, and our parent component creates a clone (I think this would be the only way this can be done) of its children, and adds the desired property

Application

import React, { useState } from "react";

const RadioGroup = ({ onChange, selected, children }) => {
  const RadioOption = React.Children.map(children, (child) => {
    return React.cloneElement(child, {
      onChange,
      checked: child.props.value === selected,
      dataTestId: "some-value" // new property here
    });
  });
  return <div className="RadioGroup">{RadioOption}</div>;
};

const RadioOption = ({ value, checked, onChange, children }) => {
  return (
    <div className="RadioOption ">
      <input
        id={value}
        type="radio"
        name={value}
        value={value}
        checked={checked}
        onChange={(e) => {
          onChange(e.target.value);
        }}
      />
      <label htmlFor={value}>{children}</label>
    </div>
  );
};

export default function App() {
  const [selected, setSelected] = useState("");
  return (
    <div className="App">
      <h1>How did you hear about our company?</h1>
      <RadioGroup onChange={setSelected} selected={selected}>
        <RadioOption value="Option 1">Option 1</RadioOption>
        <RadioOption value="Option 2">Option 2</RadioOption>
      </RadioGroup>
    </div>
  );
}

and would expect this to be the html generated after rendering

Expected HTML output

<div class="App">
    <h1>How did you hear about our company?</h1>
    <div class="RadioGroup">
        <div data-test-id="some-value" class="RadioOption ">
            <input id="Option 1" type="radio" name="Option 1" value="Option 1">
            <label for="Option 1">Option 1</label>
        </div>
        <div data-test-id="some-another-value" class="RadioOption ">
            <input id="Option 2" type="radio" name="Option 2" value="Option 2">
            <label for="Option 2">Option 2 </label>
        </div>
    </div>
</div>

However, obviously the example above does not produce this result, and I don't know how to do it and if there is a possibility for this.

in short, it needs an approach where it would not be necessary to change the components themselves, as I do not have access to them

FAQ: Why don't you just change the child components to accept this property (dataTestId) from their parents?

Because I have no control over some of these components, they are defined in a third-party library

I appreciate any and all help thanks

0

There are 0 best solutions below