Alejandro
Alejandro

Reputation: 2326

React.js - Creating Simple Accordion example

I'm relevantly new to React and I am having trouble on how to tackle this logic:

Essentially I am creating a table using flexbox, and I also want it so that when you click on one of the rows, it expands and reveals another row (for example, it will give a small description what it is about).

So far what I have is just the table.

class Application extends React.Component {
  render() {
    const renderDataRows = (
      [
                <div key={0} className='row'>
                    <div className='cell description'> Mortage Bill
                    </div>
                    <div className='cell amount'>$0,000,000</div>
                    <div className='cell amount'>$2.50</div>
                    <div className='cell amount'v>000%</div>
                </div>,
                <div key={1} className='row'>
                    <div className='cell description'> Electric Bill
                    </div>
                    <div className='cell amount'>$0,000,000</div>
                    <div className='cell amount'>$2.50</div>
                    <div className='cell amount'v>000%</div>
                </div>,
      ]
        )


    const containerTable = (
            <div className='table-container'>
                {renderDataRows}
            </div>
        )
    return (
      <div>
        {containerTable}
      </div>
    )
  }
}

More specifically, what would be the best way to structure the hidden rows? Create as a child of the cells, or siblings?

I am assuming I will need state to keep in track what is current open, etc?

I've attached Codepen link to mess around

Upvotes: 0

Views: 2363

Answers (1)

sidag95
sidag95

Reputation: 101

This can be done in the following way:

Let all the cells be in a single parent div and let the cell description be another sibling div (although using would be better). Put a class on the sibling div such as hidden. Not add a click handler on the cells div. Whenever this div is clicked, update the state with that div's id/key. Now use this to set the hidden class to the other divs. Compare this.state.key with the current id/key and show or hide accordingly. I am not giving the specific code.

Note: Instead of storing the divs in the renderDataRows, just put the data in it and map over it to create all the divs. That way you can easily manipulate the hidden class and any other variation in a single place without having to update it separately for each row of data.

Upvotes: 1

Related Questions