Jeremy
Jeremy

Reputation: 350

How can I return a div from forEach inside map function?

I am building a new component in React to display filters. My filter data looks like this:

{countries: [0: {value: 'England'}, 1: {value: 'Australia'}], continents: []}

In my render function I want to return a div for each value inside an object (England, Australia). Currently, I don't get anything rendered to the Dom.

render() {
        const {i18n, t} = this.props;
    
        return <div className={'filter'}>
            <ul className={'filter-list'}>
                {
                    Object.keys(this.props.filters).map(i => {
                        this.props.filters[i].forEach(
                            element => {
                                console.log('element', element)
                                return <p>{element.value}</p>
                            }
                        )
                    })
                }
            </ul>
        </div>;
    }

Does anyone know how I could achieve this/return the value properly?

Upvotes: 0

Views: 901

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 84912

forEach does not return anything. You'll need to use map instead:

{
  Object.keys(this.props.filters).map((i) => {
    // Switched to .map and added `return`
    return this.props.filters[i].map((element) => {
      return <p>{element.value}</p>;
    });
  });
}

This code will create a 2 dimensional array of elements, but react supports that.

Upvotes: 1

Related Questions