Search code examples
reactjswordpressheadless-cms

React function based component wont return component inside nested map function


I am trying to output different components based on the inputType, however the component or anything that goes into the DOM does not render (aka console.logs fire correctly to confirm the if/if else statements are working correctly. Not quite sure how to resolve as we cannot move it into a class based component because you cannot use react hooks inside a class based component and we currently use the useStaticQuery react hook to query WordPress.

    const ServiceQuestions = filter => {
    const { allWpService } = useServiceQuery()

    const renderQuestions = id => {
        allWpService.nodes.map(service => {
        if (service.id === id.filter) {
            service.serviceQuestions.questions.map(question => {
            question.questionInputField.map(inputField => {
                if (inputField.inputType === "text") {
                console.log(inputField.inputType)
                } else if (inputField.inputType === "number") {
                console.log(inputField.inputType)
                } else if (inputField.inputType === "radio") {
                return <InputCheckboxImageTop />
                } else {
                console.log("Cannot determine the inputType")
                }
            })
            })
        }
        })
    }

    return <>{renderQuestions(filter)}</>
    }

Solution

  • As per a comment suggested above, I removed the nested maps and instead used forEach loops which worked a charm, so for future reference here's the solution:

    const ServiceQuestions = filter => {
        const { allWpService } = useServiceQuery()
    
        const renderQuestions = id => {
        allWpService.nodes.map(service => {
            if (service.id === id.filter) {
            service.serviceQuestions.questions.forEach(data => {
                data.questionInputField.forEach(field_data => {
                if (field_data.inputType === "text") {
                    console.log(field_data.inputType)
                } else if (field_data.inputType === "number") {
                    console.log(field_data.inputType)
                } else if (field_data.inputType === "radio") {
                    return <InputCheckboxImageTop />
                } else {
                    console.log("Cannot determine the inputType")
                }
                })
            })
            }
        })
        }
    
        return <>{renderQuestions(filter)}</>
    }