DEV Community

Lucas Cruz
Lucas Cruz

Posted on

Substituindo ternários por switch-case em React-Native

Recentemente lendo alguns posts sobre react-native encontrei uma forma de melhorar um componente. Originalmente, eu o havia implementado com ternários, mas como se tratava de múltiplos estados possíveis tornava o código difícil de entender e manter.

stateModal === "wait" ? <>...</> 
: 
stateModal === edit ? <>...</> 
: 
stateModal === "delete" ? <>...</> 
:
stateModal === "finish" ? <>...</> 
: null

Enter fullscreen mode Exit fullscreen mode

Basicamente eu tenho um componente de modal que tem alguns estados: wait, edit, delete, finish

A forma que encontrei para melhorar.

Definindo switch-case

const switchModalState = () => {
        switch (stateModal) {
            case "wait":
                return (
                  <>...</>
                    )    

            case "edit":
                return (
                    <>...</>
                    )

            case "delete":
                return (
                    <>...</>
                    )

            case "finish":
                return (
                    <>...</>
                )

            default:
                return (
                    <>...</>
                    )
        }


    }
Enter fullscreen mode Exit fullscreen mode

Chamando função para renderizar

return(
        <Modal
        visible={modalVisible}
        animationType="slide"
        transparent={true}
        onRequestClose={() => setModalVisible(false)}
        >
            <View style={styles.modalContainer}>
                <View style={styles.modalContent}>
                    {switchModalState()}
                </View>
            </View>
        </Modal>

        )
}
Enter fullscreen mode Exit fullscreen mode

Concluindo

Dessa forma fica mais simples para que outros desenvolvedores entendam o código e também facilita a manutenção, tornando mais fácil adicionar estados novos, ou editar um estado específico. Investir tempo em uma estrutura bem definida para lidar com os estados do modal não apenas facilita o trabalho para mim como desenvolvedor, mas também para qualquer pessoa que precise entender ou modificar o código no futuro.

Se quiser visualizar o código atualmente: https://github.com/olucascruz/control_equip/blob/main/src/components/ModalEditDelete.jsx

Refs:
https://dev.to/girordo/algumas-das-melhores-praticas-que-utilizo-diariamente-41c4
https://stackoverflow.com/questions/46592833/how-to-use-switch-statement-inside-a-react-component

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay