Estoy creando un componente React (SocialLink) y me pregunto si este es el enfoque mejor/limpio.
const SocialLink = ({ url, type, title }: Props) => { const renderIcon = () => { let icon; switch (type) { case 'email': icon = <EmailIcon />; break; case 'twitter': icon = <TwitterIcon />; break; case 'facebook': icon = <FacebookIcon />; break; case 'whatsapp': icon = <WhatsAppIcon />; break; default: } return icon; }; const renderUrl = () => { let socialUrl; switch (type) { case 'email': socialUrl = `mailto:?subject=${title} &body=${url}`; break; case 'twitter': socialUrl = `https://twitter.com/share?text=${title}&url=${url}`; break; case 'facebook': socialUrl = `http://www.facebook.com/sharer.php?u=${url}&t=${title}`; break; case 'whatsapp': socialUrl = `whatsapp://send?text=${title} ${url}`; break; default: } return socialUrl; }; return ( <a href={renderUrl()} target="_blank" rel="noopener noreferrer" title={title}> {renderIcon} </a> ); }; Como puede ver, tengo dos declaraciones switch/case . ¿Hay alguna manera inteligente de combinarlos en uno?
Qué tal si:
const SocialLink = ({ url, type, title }: Props) => { let icon; let socialUrl; switch (type) { case 'email': icon = <EmailIcon /> socialUrl = `mailto:?subject=${title} &body=${url}`; break; case 'twitter': // etc } return ( <a href={socialUrl} /* ... */> {icon} </a> ) }Creo que podemos definir un valor constante porque podría ser estático. Será más legible y mantenible.
const socialLinks = { email: { icon: <EmailIcon />, socialUrl: `mailto:?subject=${title} &body=${url}` }, twitter: { icon: <TwitterIcon />, socialUrl: `https://twitter.com/share?text=${title}&url=${url}` }, .... }; const SocialLink = ({ url, type, title }: Props) => { return ( <a href={socialLinks[type].socialUrl} target="_blank" rel="noopener noreferrer" title={title}> {socialLinks[type].icon} </a> ); };¿Qué opinas sobre este enfoque?
por supuesto, la variable de datos se puede importar desde una carpeta CONSTANTS o algo así, de esta manera todo quedará claro
const data = { email: { icon: <EmailIcon />, socialUrl: (title, url) => { return `mailto:?subject=${title} &body=${url}`; } }, twitter: { icon: <TwitterIcon />, socialUrl: (title, url) => { return `https://twitter.com/share?text=${title}&url=${url}`; } }, facebook: { icon: <FacebookIcon />, socialUrl: (title, url) => { return `http://www.facebook.com/sharer.php?u=${url}&t=${title}`; } }, whatsapp: { icon: <WhatsAppIcon />, socialUrl: (title, url) => { return `whatsapp://send?text=${title} ${url}`; } } }; export const SocialLink = ({ url, type, title }) => { return ( <a href={data[type].socialUrl(title, url)} target="_blank" rel="noopener noreferrer" title={title} > {data[type].icon} </a> ); };