0

I have the following code snippet that works fine in the console, but it's not displaying to the screen. Any help is appreciated.

{Object.keys(flags).forEach(product => {
    return (
        <>
            <input
                type='checkbox'
                className='form-checkbox'
                name={product}
                value={product}
                onChange={this.gatherFormData}
            />
            <span className='label'>{product}</span>
        </>
    );
})}

The product key is not displaying on the screen, even though I can see it just fine within the console.

Update: Thought I'd update this question to give the answer below since no-one posted their solution from the all the comments made.

The following uses the .map loop rather than .forEach loop, since the .forEach loop does not output content to the screen. If you want to see the results, you'll have to console.log it to the screen.

{Object.keys(flags).map(product => {
    return (
        <>
            <input
                type='checkbox'
                className='form-checkbox'
                name={product}
                value={product}
                onChange={this.gatherFormData}
            />
            <span className='label'>{product}</span>
        </>
    );
})}
pingeyeg
  • 632
  • 2
  • 6
  • 23
  • 7
    The value `return`ed from a `.forEach` is *totally ignored*. Did you mean `.map`? – jonrsharpe Mar 11 '19 at 20:52
  • Well I'll be... switching .forEach to .map fixed the issue. Man, that was simple. I didn't realize .forEach wouldn't output data. Thanks! – pingeyeg Mar 11 '19 at 20:55

2 Answers2

2

Should it not be:

return (
    <div> // needs an element wrapper
        <input
            type='checkbox'
            className='form-checkbox'
            name={product}
            value={product}
            onChange={this.gatherFormData}
        />
        <span className='label'>{product}</span>
    </div>
);

As jonrsharpe says - you also need to use map (forEach simply iterates over the values - but doesn't return anything)

{Object.keys(flags).map(product => {
jsdeveloper
  • 3,945
  • 1
  • 15
  • 14
1

Return inside .forEach does nothing either push data to an array to use it later or return from a .map method instead

Here is an example if you need to use .forEach as in your question...

{
const products = [];
Object.keys(flags).forEach(product => {
  products.push (
    <>
        <input
            type='checkbox'
            className='form-checkbox'
            name={product}
            value={product}
            onChange={this.gatherFormData}
        />
        <span className='label'>{product}</span>
    </>
  );
})
return products;
}
Nawwar Elnarsh
  • 1,049
  • 16
  • 28