0

Here value prop is ["hello world"]

it's a simple array of one value string and the given function below is not returning JSX.

const list = ({value}) => {
    return (
        <div>
        {
            value.forEach(function(item, index, array) {
                console.log(item, index)
                return <div>{item}</div>
            })
        }
        </div>
    );
}

export default list;
Soenderby
  • 157
  • 1
  • 11
techgeek
  • 11
  • 1
  • 3
  • `forEach()` returns `undefined` use `map()` instead – zb22 Nov 11 '20 at 09:18
  • The code will return a jsx element as long as the file it is exported from is .jsx / .tsx and not .js / .ts A few notes to your code: - The array `value` should be called `values` since it is an array and holds multiple values. - Use `.map` instead of `forEach` - Use proper indentation to avoid confusion. - Don't know why you would put a console.log in the returning jsx. If you want to check the values, then console.log before returning or use the debugger to avoid confusion. – BaconPancakes Nov 11 '20 at 09:22

1 Answers1

1

forEach is doesn't return anything. you should use Array.map instead!

const list = ({ value = [] // Default value }) => {
    return (
        <div>
        {
            value.map((item, index) => {
                console.log(item, index)
                return <div>{item}</div>
            })
        }
        </div>
    );
}

export default list;

Naren
  • 4,152
  • 3
  • 17
  • 28
  • if map is used then it says "Objects are not valid as a React child. If you meant to render a collection of children, use an array instead " – techgeek Nov 11 '20 at 09:20
  • What does `value` contains? – Naren Nov 11 '20 at 09:22
  • you'll get that error if you render directly Object `{}` instead of values, If you can show the placeholder data, we can see!! – Naren Nov 11 '20 at 09:23