简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM