'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 1:[1]
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)}</>
}
Solution 2:[2]
Your renderQuestions function doesn't return the result array
You can replace
const renderQuestions = id => {
allWpService.nodes.map(service => {
by
const renderQuestions = id => {
return allWpService.nodes.map(service => {
or use parentheses instead of curly brackets around your allWpService.nodes.map
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Daniel Vickers |
Solution 2 | Maneal |