Reactjs function not returning JSX

Viewed 385

I am trying to write a function to return JSX, but it does not work, somehow. Are there any conflicts why my function is not returning any value. I've tried strings, lists, but it seems that nothing is returning.

My function:

const modifyScores = () => {
        teams.map(team => {
            if (team.team_name === activeTeam) {
                let scoresList = []

                Object.entries(team).map(([key, value]) => {
                    if (key.startsWith('r')) {
                        const obj = {"round": parseInt(key.substring(1)), "score": value}
                        scoresList.push(obj)
                    }
                })

                scoresList.sort((a, b) => a.round - b.round)
                
                console.log(scoresList)
                //return <Button>test</Button>
                return scoresList.map(s => <Button>r: {s.round}</Button>)
            }
        })
}

My JSX:

{modifyScores()}
2 Answers

You should do return inside modifyScores().

const modifyScores = () => {
    return teams.map(team => {
            if (team.team_name === activeTeam) {
                let scoresList = []

                Object.entries(team).map(([key, value]) => {
                    if (key.startsWith('r')) {
                        const obj = {"round": parseInt(key.substring(1)), "score": value}
                        scoresList.push(obj)
                    }
                })

                scoresList.sort((a, b) => a.round - b.round)
                
                console.log(scoresList)
                //return <Button>test</Button>
                return scoresList.map(s => <Button>r: {s.round}</Button>)
            }
        })
}

You have two options.

  1. explicitly return the result of teams.map() inside of modifyScores() by prepending a return statement return teams.map()
  2. remove the curly braces around ... => {teams.map()}, which will return the result implicitly.

modifyScores() => teams.map();

For details take a look at the syntax of arrow functions at the MDN referrence

Related