Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
24
rated 0 times [  26] [ 2]  / answers: 1 / hits: 18547  / 7 Years ago, sun, october 1, 2017, 12:00:00

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


More From » reactjs

 Answers
330

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>




[#56338] Thursday, September 28, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anabeldaliad

Total Points: 552
Total Questions: 107
Total Answers: 120

Location: Hungary
Member since Mon, Feb 21, 2022
2 Years ago
;