1

I'm looking to try and transform the outputted value of a JSX attribute from a string to an expression/function call.

Given the source code looks something like...

function dynamicClasses() {
    //... do something
}

export default () => <div dynamic="hello world"></div>

The desired output after Babel has translated the code would be...

function dynamicClasses() {
    //... do something
}

export default () => <div class={dynamicClasses("hello world")}></div>

I've got the following which finds the attribute, but I'm struggling to replace the string value with a expression/function call.

const convertClassNameIntoDynamicStyles = ({types: t}) => {
    return {
        visitor: {
            JSXOpeningElement(path) {
                path.get('attributes').forEach(attribute => {
                    if (attribute.node.name.name === 'dynamic') {
                        const classNames = attribute.node.value;

                        attribute.remove();

                        path.node.attributes.push(t.JSXAttribute(
                            t.JSXIdentifier('class'),
                            `myFunctionCallHere(${classNames})`
                        ));
                    }
                })
            },
        },
    }
}

module.exports = convertClassNameIntoDynamicStyles;

Line 13 where it's myFunctionCallHere(${classNames}) is what I cannot figure out how to turn into an AST style expression, whats the correct way to do this?

Thanks

owenmelbz
  • 6,180
  • 16
  • 63
  • 113

0 Answers0