Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React JSX iterate over array of string and print message

I have a function component as below;

const MyFunctionComponent = ({status}) => {
let consolidatedErrorMsg = status.errorMessage.split("-"); //['Error line 1', 'Error line 2']
    return (
        <div>
            {status.status && (
                <div>
                    <p>
                        <Icon
                            name={status.status === 'success' ? 'success' : 'error'}
                        />
                    </p>
                    {
                        consolidatedErrorMsg.forEach((msg, i) => {
                            <div>{msg}</div>
                        })
                    }
                </div>
            )}
        </div>
    )
};

Now, within this function component, I am trying to iterate and print "consolidatedErrorMsg" which is an array of strings as I have shown above. However, for some reason, it is not working.

Seems like some syntax issue while iterating. Please help.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use map() since forEach() does nothing with it’s returned value.

You’ve also used {} so add the return keyword, or replace with () as shown in the demo below.



const MyFunctionComponent = () => {

    const consolidatedErrorMsg = ['Error line 1', 'Error line 2'];

    return (
        <div>
            <h1>{'Example'}</h1>
            {
                consolidatedErrorMsg.map((msg, i) => <div key={msg}>{msg}</div>)
            }
        </div>
    )
}
ReactDOM.render(<MyFunctionComponent />, document.getElementById("react"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading