How to render list of list in react?
Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error How to render list of list in react? on this date .
I have data in for of list of lists and I want to render it in the view.
The data:
{ "blocks_content": [ [ " Bakery", " Company GbR", ], [ "Bill no.3-7721 11:29:51 20.04.2021" ], [ "1x Cappuccino 2,70€ 2,70€ A" ], ] }
I tried like this but I am not seeing any error or warning. what I could be missing?
return ( <Container> .... { fileBlocks !== null && <Form.Field> <Label>{fileBlocks["name"]}</Label> {fileBlocks["blocks_content"].forEach((element, index) => { <List key={index}> { element.forEach((line, i) => { <List.Item key={i}> {line} </List.Item> }) } </List> })} </Form.Field> } ... </Container> );
Answer
forEach
only processes arrays in place but doesn’t return anything. map
returns a new array of combined array information and JSX which React can use in the render.
function Example({ data }) { return ( <div> {data.blocks_content.map(arr => { return ( <ul> {arr.map((line, i) => <li key={i}>{line}</li>)} </ul> ) })} </div> ); } const data = { blocks_content: [ ['Bakery', 'Company GbR'], ['Bill no.3-7721 11:29:51 20.04.2021'], ['1x Cappuccino 2,70€ 2,70€ A'], ] }; // Render it ReactDOM.render( <Example data={data} />, 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>