Skip to content

Instantly share code, notes, and snippets.

@chrisirhc
Created March 9, 2019 05:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisirhc/1811b2a8b905b744d092083fef89cd65 to your computer and use it in GitHub Desktop.
Save chrisirhc/1811b2a8b905b744d092083fef89cd65 to your computer and use it in GitHub Desktop.
Convert jsx arrays
'use strict';
module.exports = function(file, api, options) {
const j = api.jscodeshift;
const root = j(file.source);
const ReactUtils = require('./utils/ReactUtils')(j);
function makeSafe(node) {
if (node.type !== 'JSXElement') {
return j.jsxExpressionContainer(node);
}
return node;
}
function convertArray(node) {
if (node.parentPath.value.type === 'JSXAttribute') {
return node.value;
}
const {elements} = node.value.expression;
return elements.map(makeSafe);
}
if (
options['explicit-require'] === false ||
ReactUtils.hasReact(root)
) {
const mutations = root
.find(j.JSXExpressionContainer, {
expression: {
type: 'ArrayExpression',
},
})
.replaceWith(convertArray)
.size();
if (mutations) {
return root.toSource();
}
}
return null;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment