nirav dhanorkar
nirav dhanorkar

Reputation: 175

Reactjs - want to print dynamic element

I am trying to create a dynamic element. whatever user input in an input box, the same number of LI element will create. I get this output when I enter 2 in input box.

<li key=0>input 0</li><li key=1>input 1</li>

where I want two li elements.

import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      times: 0
    };
  }
  createList = event => {
    let times = event.target.value;
    this.setState({
      times
    });
  };

  getData = times => {
    let str = "";
    for (let i = 0; i < times; i++) {
      str += "<li key=" + i + ">input " + i + "</li>";
    }
    return <ul>{str}</ul>;
  };
  render() {
    return (
      <div className="App">
        <p className="App-intro">
          <input type="number" onChange={this.createList} />
          {this.getData(this.state.times)}
        </p>
      </div>
    );
  }
}
export default App;

Upvotes: 2

Views: 1474

Answers (1)

Mayank Shukla
Mayank Shukla

Reputation: 104399

This is because you are treating them as string instead of DOM node elements. Use an array and push all the elements inside that and return the final result.


Don't forgot you are writing JSX, and <li> input: {i+1} </li> will get converted into:

React.createElement(
  "li",
  null,
  "input: ",
  i+1
);

But if you write: "<li>input: {i+1}</li>", it will be treated as a string.

Check the complied code result of these two cases by Babel REPL.

Solution:

Write it like this:

getData = times => {
    let str = [];
    for (let i = 0; i < times; i++) {
      str.push(<li key={i}> input: {i+1} </li>);
    }
    return <ul>{str}</ul>;
};

Upvotes: 2

Related Questions