Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

provide example on how to manipulate custom template props #952

Open
headfire94 opened this issue Mar 29, 2024 · 2 comments
Open

provide example on how to manipulate custom template props #952

headfire94 opened this issue Mar 29, 2024 · 2 comments

Comments

@headfire94
Copy link

🚀 Feature Proposal

There is lack of custom template examples, for example how to generate component that accepts size props and applies it to both width and height

@iAmMuneeb
Copy link

@headfire94 were you able to figure it out?

@headfire94
Copy link
Author

@iAmMuneeb not i use kinda ugly solution:

module.exports = ({ componentName, props, jsx, imports, interfaces, exports }, { tpl }) => {
  // Find or create the width and height attributes in the jsx object

  const reactImport = `import React from 'react'`
  const widthAttribute = jsx.openingElement.attributes.find((attr) => attr.name.name === 'width')
  const heightAttribute = jsx.openingElement.attributes.find((attr) => attr.name.name === 'height')
  const widthValue = widthAttribute?.value?.expression?.value || 24
  const heightValue = heightAttribute?.value?.expression?.value || 24

  if (widthAttribute) {
    widthAttribute.value = {
      type: 'JSXExpressionContainer',
      expression: { type: 'Identifier', name: 'width' },
    }
  } else {
    jsx.openingElement.attributes.push({
      type: 'JSXAttribute',
      name: { type: 'JSXIdentifier', name: 'width' },
      value: { type: 'JSXExpressionContainer', expression: { type: 'Identifier', name: 'width' } },
    })
  }

  if (heightAttribute) {
    heightAttribute.value = {
      type: 'JSXExpressionContainer',
      expression: { type: 'Identifier', name: 'height' },
    }
  } else {
    jsx.openingElement.attributes.push({
      type: 'JSXAttribute',
      name: { type: 'JSXIdentifier', name: 'height' },
      value: { type: 'JSXExpressionContainer', expression: { type: 'Identifier', name: 'height' } },
    })
  }

  const widthExp = `const width = size || props.width || ${widthValue};`
  const heightExp = `const height = size || props.height || ${heightValue};`
  return tpl`
${reactImport}
${imports}
${interfaces}

function ${componentName}({ size, ...props }) {
  ${widthExp}
  ${heightExp}

  return ${jsx};
}

export default React.memo(${componentName})
  `
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants