Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - Dynamic creation of List item inside component

Is there any way to add dynamical li element into my ul list ? I'd like add my li by clicking the button. Here is example code

class Component1 extends React.Component {

    constructor() {
        super();
    }

    add() {
        let ul = document.getElementById('mylist');
        let li = document.createElement('li');
        li.appendChild(document.createTextNode({some_variables});
        ul.appendChild(li);
    }
    render() {
        return (
                <a href="#" onClick={() => this.add()}>Add</a>
                <ul id="mylist">
                    /* dynamic list ITEM  */

                </ul>
        );
    }
}

ReactDOM.render(<Component1 />, document.getElementById('root'));

Of course current function add() doesn't work on React

like image 431
Szach Avatar asked Oct 01 '17 16:10

Szach


1 Answers

When using react we are not "touching" the DOM as we usually do with other libraries (like jQuery).
One of the best and core features of react is the virtual DOM, the Reconciliation & diffing algorithm

React builds and maintains an internal representation of the rendered UI. It includes the React elements you return from your components. This representation lets React avoid creating DOM nodes and accessing existing ones beyond necessity, as that can be slower than operations on JavaScript objects. Sometimes it is referred to as a “virtual DOM”

In react you create components (functions) that renders / returns a jsx (markup).
A simple example to your scenario could be:

const ListItem = ({ value, onClick }) => (
  <li onClick={onClick}>{value}</li>
);

const List = ({ items, onItemClick }) => (
  <ul>
    {
      items.map((item, i) => <ListItem key={i} value={item} onClick={onItemClick} />)
    }
  </ul>
);

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      inputValue: '',
      fruites: ['Apple', 'Banana', 'Orange']
    };
  }

  onClick = () => {
    const { inputValue, fruites } = this.state;
    if (inputValue) {
      const nextState = [...fruites, inputValue];
      this.setState({ fruites: nextState, inputValue: '' });
    }
  }

  onChange = (e) => this.setState({ inputValue: e.target.value });

  handleItemClick = (e) => {console.log(e.target.innerHTML)}

  render() {
    const { fruites, inputValue } = this.state;
    return (
      <div>
        <input type="text" value={inputValue} onChange={this.onChange} />
        <button onClick={this.onClick}>Add</button>
        <List items={fruites} onItemClick={this.handleItemClick} />
      </div>
    );
  }
}


ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
like image 66
Sagiv b.g Avatar answered Nov 15 '22 07:11

Sagiv b.g