Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to append dynamically to a <ul></ul> in reactJS

Tags:

reactjs

I wanted to make a todo application as I'm a beginner in ReactJS (& yes I am learning it all by myself and I'm in high school!). So, I wanted to append a li to a ul!

I've tried logging the todo to the console and it worked too but now I would like to add the li to the ul

Form.js

import React, { Component } from 'react';
import '../Styles/Forms.css';

class Form extends Component {
    constructor() {
        super();
        this.state = { todo: '' };
        this.handleTodo = this.handleTodo.bind(this);
        this.handleAddTodo = this.handleAddTodo.bind(this);
    }

    render() {
        return (
            <div className='center-v-h'>
                <form>
                    <table>
                        <tbody>
                            <tr>
                                <td>
                                    <input type='text' onChange={this.handleTodo} />
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <button onClick={this.handleAddTodo} style={{ width: '100%' }}>
                                        Add Todo
                                    </button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </form>
                <ul id='todo'></ul>
            </div>
        );
    }

    handleTodo(e) {
        this.setState({ todo: e.target.value });
    }

    handleAddTodo(e) {
        e.preventDefault();
        console.log(`Todos: ${this.state.todo}`);
    }
}

export default Form;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import Form from './Components/Form';

function App() {
    return (
        <div>
            <Form />
        </div>
    );
}

ReactDOM.render(<App />, document.querySelector('#root'));

like image 833
Axitya Tripathi Avatar asked Oct 19 '25 00:10

Axitya Tripathi


1 Answers

You have state like this:

this.state = { todos: 
   [
      {id: 1, text: "Todo 1"},
      {id: 2, text: "Todo 2"},
      {id: 3, text: "Todo 3"}
   ]
}

And you can use map operator to render dynamic ul > li like this:

<ul>
   {
      this.state.todos.map(todo => {
         return <li key={todo.id}>{todo.text}</li>
      })
   }
</ul>

like image 90
aldenn Avatar answered Oct 20 '25 15:10

aldenn