Removing outer React component with jscodeshift

697 Views Asked by At

I'm working on a small project and I need to remove a specific component from a tree without removing its children.

Let's imagine the following code:

export const Component = () => {
  return (
    <>
      <Background color="red">
        <div>Red background</div>
      </Background>
      <Background color="blue">
        <div>Blue backgound</div>
      </Background>
    </>
  );
};

Using jscodesift, I would like to remove the <Background color="XXX"> opening and closing elements so that the output will be:

export const Component = () => {
  return (
    <>
      <div>Red background</div>
      <div>Blue backgound</div>
    </>
  );
};


For now, I'm stuck trying to find a way to remove the nodePath.node.openingElement and nodePath.node.closingElement without removing their children.

Does anybody know if what I'm trying to do is possible? What could help me solve this problem?

1

There are 1 best solutions below

0
Danielo515 On

You have to hoist to the parent element of the opening and closing tags (the JSXElement) and replace it with its children. A quick and dirty way can look like this:

export default function transformer(file, api) {
  const j = api.jscodeshift;

  return j(file.source)
    .find(j.JSXIdentifier, { name: "Background" })
    .filter((path) => j.JSXOpeningElement.check(path.parent.node))
    .forEach((path) => {
      j(path.parent.parent).replaceWith(path.parent.parent.get("children").value);
    })
    .toSource();
}

Playground example: https://astexplorer.net/#/gist/325d128229e633b5d11343d9ee0e86fc/latest