Search code examples
reactjsreact-hooksantdant-design-proreact-modal

How generate dynamic DOM element in React


I am getting a list of elements over the network. The list size might vary at each call. I have to show the list content in my React ant-design based site. How to generate this dynamic component ? What I did is,

export const myModal = props => {


const contactArr = [];

for(let i=1;i<=props.contactList;i++){
    const eachRow = `<Row style={{border : '1px solid red'}}>
                        <Col>
                            <Text>Test<Text>
                        </Col>
                    </Row>`
    contactArr.push(eachRow);
}

return (
    <Modal
        visible={props.isVisible}
        width={'40%'}
        onCancel={props.handleEditModalCancel}
        footer={[
            <Button key="back" onClick={props.handleContactModalCancel}>
                Cancel
            </Button>,
            <Button key="submit" type="primary" onClick={props.contactModalConfirm}>
                {/*<Button key="submit" type="primary" onClick={props.inputSubmit}>*/}
                Submit
            </Button>
        ]}
    >
        <div>
            {contactArr.join('')}

        </div>


    </Modal>
);

}

However, instead of rendered rows with columns I am getting simple string output such as,

<Row style={{border : '1px solid red'}}> <Col> <Text>Test<Text> </Col> </Row><Row style={{border : '1px solid red'}}> <Col> <Text>Test<Text> </Col> </Row><Row style={{border : '1px solid red'}}> <Col> <Text>Test<Text> </Col> </Row><Row style={{border : '1px solid red'}}> <Col> <Text>Test<Text> </Col> </Row><Row style={{border : '1px solid red'}}> <Col> <Text>Test<Text> </Col> </Row><Row style={{border : '1px solid red'}}> <Col> <Text>Test<Text> </Col> </Row>

How to get such a rendered output. Is my approach right as I know direct DOM manipulation is not good in React ? Do I need to add any key ?

What is the best way to get my desired result ?

Many thanks in advance.


Solution

  • You could use map to create React elements using your data array.

    A simple example would be like this.

    // inside your return statement.
    return (
      <div>
        {props.contactList.map(contact => { 
          return <p>{contact}</p>
        })
      </div>
    )
    

    Another example

    import React from 'react';
    
    export default function App() {
      const numbers = [1, 2, 3]
    
      return (
        <div>
         {numbers.map(num => {
           return (
             <div>
                <p>{num}</p>
             </div>
           )
         })}
        </div>
      )
    }