rmorse / babel-plugin-jsx-template-vars

A Babel transform for rendering a template version of your React / Preact app. Useful for generating a pre-render for SSR.
MIT License
10 stars 0 forks source link

Support components in list variables (which contain objects) #9

Closed rmorse closed 2 years ago

rmorse commented 2 years ago

At the moment when we configure a list variable, we need to define which props we want to expose...

What we need to do is support components in lists, and map their .templateVars as list variable props.

When used this way we wouldn't need to configure a list vars children/props as they would in effect be inherited.

Currently encountered this issue when generating a radio button group, and each radio button defines its own ID rather than getting it passed in via props...

rmorse commented 2 years ago

This has been added in v0.0.8

Now child components (inside a map) will be exposed automatically on the parent object as described in this comment: https://github.com/rmorse/babel-plugin-jsx-template-vars/issues/10#issuecomment-1138287592

const Radio = ({ className, value, children }) => {
    const [ checked, setChecked ] = useState( false );
    const uid = useInstanceId( Radio );
    return (
        <>
            <input type="radio" id={ uid } className={className} value={value} checked={checked} />
            <label for={ uid }>{children}</label>
        </>
    );
};
Radio.templateVars = ["checked", "value", "uid", "children"];

const App = ({ title }) => {
    const radios = [ 
        { value: 'radio1', label: 'Radio 1' },
        { value: 'radio2', label: 'Radio 2' },
    ];

    return (
        <>
            <h1>{title}</h1>
            <div>
                { radios.map( ( radio ) => (
                    <Radio className="my-radio" value={radio.value}>{radio.label}</Radio>
                ) ) }
            </div>
        </>
    );
};
App.templateVars = ["title", ["radios", {type: "list"} ]];