How can I display an HTML button using the return from a javascript function?

Issue

I trying to have my function return HTML button tags that will be displayed on the page like so:

enter image description here

(without the hover thing)

The problem is that as you can see every row has different buttons, so I wanted to make a function that takes in the parameter the "category" of the row, for example the "Games" row has 2 buttons: Modify and Delete.

Here’s my javascript code:


function Category(cat) {
    if (cat == "games") {
        let innerhtml = `<div className='game_buttons'> <button className='modify'>Modify</button> <button className='delete'>Delete</button> </div>`
        return innerhtml
    }


    if (cat == "upcoming") {
        let innerhtml = `<div className='game_buttons'>  <button className='released'>Released</button> <button className='modify'>Modify</button> <button className='delete'>Delete</button> </div>`
        return innerhtml
    }


    if (cat == "featured") {
        let innerhtml = `<div className='game_buttons'> <button className='delete'>Delete</button> </div>`
        return innerhtml
    }
}


I placed that same function where I need it to be displayed, like so :


                    <div className='game_buttons'>
                        {Category("games")}
                    </div>

But I get this :
enter image description here

So how could I display this buttons instead of just getting the HTML tags as text?

Solution

React purposefully makes injecting HTML strings cumbersome to try and steer you towards "thinking in React."

Here, this means just creating another component that conditionally renders the content you want as JSX.

function Category(props) {
    if (props.cat === "games") {
        return (
            <div className="game_buttons">
                <button className="modify">Modify</button>
                <button className="delete">Delete</button>
            </div>
        );
    }

    if (props.cat === "upcoming") {
        return (
            <div className="game_buttons">
                <button className="released">Released</button>
                <button className="modify">Modify</button>
                <button className="delete">Delete</button>
            </div>
        );
    }

    if (props.cat === "featured") {
        return (
            <div className="game_buttons">
                <button className="delete">Delete</button>
            </div>
        );
    }
}

Then, render Category and pass in your cat prop:

<Category cat="games" />

Answered By – romellem

Answer Checked By – Timothy Miller (AngularFixing Admin)

Leave a Reply

Your email address will not be published.