简体   繁体   中英

Is there a better way of adding divs dynamically to a existing element?

As a part of implementing a emailing app, I am trying to load all the emails from a API and display them to the user. I achieve this by running a forEach loop in which I which create a email element, fill in the relevant details and append it to a container. The container is then appended to a existing view.

Is there a more optimized (faster and cleaner) way to achieve this, by using either vanilla JS or React?

fetch(`/emails/${mailbox}`)
  .then(response => response.json())
  .then(emails => {
    var enc = document.createElement('div');
    enc.className = "enc";
    
    emails.forEach(element => {
      let name = document.createElement('div');
      name.className = "name";
      name.innerHTML = element.sender;

      let subject = document.createElement('div');
      subject.className = "subject";
      subject.innerHTML = element.subject;

      let timestamp = document.createElement('div')
      timestamp.className = "timestamp";
      timestamp.innerHTML = element.timestamp;

      let container = document.createElement('div');
      container.className = "email-container";
      container.appendChild(name);
      container.appendChild(subject);
      container.appendChild(timestamp);

      enc.appendChild(container);
    });
    document.getElementById('emails-view').appendChild(enc)
});

Since you are using React, there is no reason to use JS native DOM methods for DOM manipulation. Take advantage of react's jsx syntax.

Here is your example written as a component that loads data on component initialization:

function EmailViewComponent() {
  const [emails, setEmails] = useState([])

  useEffect(() => {
    const apiCall = fetch(`/emails/${mailbox}`)
      .then(response => response.json())
      .then(emails => {
        setEmails(emails)
      });
  }, [])

  return (
    <div className="emails-view">
      <div className="enc">
        {emails.map(emailItem => (
          <div className="email-container">
            <div className="name">{emailItem.sender}</div>
            <div className="subject">{emailItem.subject}</div>
            <div className="timestamp">{emailItem.timestamp}</div>
          </div>
        ))}
      </div>
    </div>
  )
}

In this way you will be able to maintain applications way easier and cleaner.

As for the performance, i am not sure which is faster, but i would always go with convenience to write cleaner code as a trade off.

But i am sure that React team pays attention to performance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM