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 Use param in function outside of event

I’m trying to take a function out of an onClick event but i don’t know why it’s not working.

This code works

<ul className="list-group mt-3">
    {news.map((item) => (
        <li 
            key={item.name} 
            className="list-group-item text-capitalize"
        > 
            {item.name}
            <button 
                className="btn btn-dark btn-sm float-right"
                onClick={ () => dispatch( newsAction(item.url) ) }
            >
                Info
            </button>
        </li>
    ))}
</ul>

But i’m trying to cleanUp the code using this

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

const handleGetInfo = (url) => {
    dispatch( newsAction(url) )
}

return (
    <ul className="list-group mt-3">
        {news.map((item) => (
            <li 
                key={item.name} 
                className="list-group-item text-capitalize"
            > 
                {item.name}
                <button 
                    className="btn btn-dark btn-sm float-right"
                    onClick={ handleGetInfo }
                >
                    Info
                </button>
            </li>
        ))}
    </ul>
)

And it throws a 404 error when calling the API

>Solution :

const handleGetInfo = (url) => () => {
    dispatch( newsAction(url) )
}

return (
    <ul className="list-group mt-3">
        {news.map((item) => (
            <li 
                key={item.name} 
                className="list-group-item text-capitalize"
            > 
                {item.name}
                <button 
                    className="btn btn-dark btn-sm float-right"
                    onClick={ handleGetInfo(item.url) }
                >
                    Info
                </button>
            </li>
        ))}
    </ul>
)
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