Source:  Twitter logo

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>
    )
  }
};

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.

7 users liked answer #0dislike answer #07
justelouise profile pic
justelouise

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).