Dipesh Chaulagain
Dipesh Chaulagain

Reputation: 105

How to dynamically put contents on react render

I know that we can use docoment object to create elements dyanamically in the vanilla js and append that element to some parent element. After doing some research i found this is not the preferred way to do in react. I need help with this!

h2 element from value of 'data' in ComponentDidMount sould be made and append as a second child to to the div in the render.



import React, { Component } from 'react';

class App extends Component {
  componentDidMount() {
    const data = 'This should be the header 2';

    //h2 element from value of 'data' sould be made and append as a second child to to the div in the render
  }

  render() {
    return (
      <div className='main'>
        <h1>Adding Child Elements</h1>
        {/* This is where the created element should be inserted */}
        <p>This is a second child</p>
      </div>
    );
  }
}

export default App;

Upvotes: 2

Views: 139

Answers (1)

Taki
Taki

Reputation: 17654

Use the component's state, add a key heading , empty at first , then fill it up when the comopnent mounts :

import React, { Component } from "react";

class App extends Component {
  state = {
    heading : "",
    loaded: false
  }

  componentDidMount() {
    const data = "This should be the header 2";

    this.setState({ heading : data, loaded : true});

    //h2 element from value of 'data' sould be made and append as a second child to to the div in the render
  }

  render() {
    return (
      <div className="main">
        <h1>Adding Child Elements</h1>
        {/* This is where the created element should be inserted */}
        {this.state.loaded ? <h2>{this.state.heading}</h2>: null }
        <p>This is a second child</p>
      </div>
    );
  }
}

export default App;

Upvotes: 1

Related Questions