0

I have a component that renders a list. Each item has a classname. My question is how can I dynamically add a classname followed by an incrementing value.

function Menu(props) {
    const list = ['list1', 'list2', 'list3']
    const menuitems = list.map((list, index) => {
        return <li className="menuitem" key={index}>{list}</li>
    })

    return (
        <ul>{menuitems}</ul>
    )
}

In the DOM, it should look like this:

<ul>
    <list class="menuitem item-1">list1</li>
    <list class="menuitem item-2">list2</li>
    <list class="menuitem item-3">list3</li>
</ul>
1
  • You can add a incrementing value as the state of the class and increase every time you want dynamically add a classname, so create a function that add to the list this classname. The renderPart of the list you already have done it. Commented Sep 18, 2019 at 10:27

5 Answers 5

3

It's pretty simple =)

function Menu(props) {
    const list = ['list1', 'list2', 'list3']
    const menuitems = list.map((list, index) => {
        return <li className={`menuitem item-${index + 1}`} key={index}>{list}</li>
    })

    return (
        <ul>{menuitems}</ul>
    )
}

It uses JSX Expression { - expression code lives here - }. You can place any valid JS expression between curly braces.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm glad to help!
2

Try This :

function Menu(props = null) {
    const list = ['list1', 'list2', 'list3']
    const menuitems = list.map((list, index) => {
        return `<li className="menuitem item-${index + 1}" key="${index}">${list}</li>`
    });

    return (
        `<ul>${menuitems.join(" ")}</ul>`
    )
}

Comments

1

You could use package called classnames or:

<li className={`menuitem-${index}`} key={index}>{list}</li>

1 Comment

This is hhelpful too. Thank you.
1

Try this

const menuitems = list.map((list, index) => {
        return <li className={`menuitem item-{index+1}`} key={index}>{list}</li>
    })

Comments

0

This should work

function Menu(props) {
    const list = ['list1', 'list2', 'list3']
    const menuitems = list.map((list, index) => {<li className=`menuitem itme-${index + 1}>{list}</li>})
    return <ul>{menuitems}</ul> 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.