React JS. Append element to the DOM

firmfiasco picture firmfiasco · Apr 13, 2018 · Viewed 21.8k times · Source

I'm new to react and I've been playing around with it the past few days. I'm trying to append a value to the DOM, I found a way to do it but I'm looking for a way to do with by

var para = document.createElement("li");
var t = document.createTextNode(value);
para.appendChild(t);
document.getElementById("root").appendChild(para); 

But, I'm looking for a different way. I tried a few different ways but I'm stuck. Is there a way other than this way above ^^^^

import React, { Component } from 'react';
import { render } from 'react-dom';


export class Parent extends React.Component {
  constructor(props) {
    this.greet = this.greet.bind(this);
    this.state = { text: " " };
  }

  greet(value) {
    //console.log(value);

    var para = document.createElement("li");
    var t = document.createTextNode(value);
    para.appendChild(t);
    document.getElementById("root").appendChild(para); 

  }

  render() {
    return (
      <div>
        <Child onGreet={this.greet} />
      </div>
    )
  }
};


export class Child extends React.Component {

  constructor(props) {
    this.state = { value: '' };
    this.handleChange = this.handleChange.bind(this);
    this.eventClick = this.eventClick.bind(this);
  }

  handleChange(event) {
    this.setState({ value: event.target.value });
  }

  eventClick() {
    this.props.onGreet(this.state.value);
  }

  render() {
    return (
      <div>
<input type="text" value={this.state.value} onChange={this.handleChange} />
<button type="button" onClick={this.eventClick}>Submit </button>
      </div>
    )
  }
};

Answer

justelouise picture justelouise · Apr 13, 2018

You can try to utilize React's state property.

import React, { Component } from 'react';
import { render } from 'react-dom';

export class Parent extends React.Component {
  constructor(props) {
    this.greet = this.greet.bind(this);
    this.state = {
      text: [],
    };
  }

  greet(value) {
    //console.log(value);

    const {text} = this.state
    return this.setState({
      text: text.concat(value),
    });

  }

  render() {
    return (
      <div>
        <Child onGreet={this.greet} />
        <ul>
        {this.state.text.map(x => (<li>{x}</li>))}
        </ul>
      </div>
    )
  }
};

With this, the list gets populated as the value of this.state.text changes.