Reputation: 341
I started to learn React and I made a to do list. With add,delete, drag&drop and edit functions.
For my edit I take list item string and place it in the input used for add and if I press add again my list item change. I would like to rewrite that function. I want to transform the list item into an input and when I press the button again I want to replace the list item value with that input.
I should use a hidden input like in Javascript ? I'm not sure if I can show/hide elements in react. Or should I create a toggle method ?
Here's my HTML code:
<div id="app"> </div>
Here's my ReactJS code:
import React, { Component } from 'react';
import {SortableContainer, SortableElement, arrayMove} from 'react-sortable-hoc';
const data=[];
const ListItem = SortableElement(({item,i,editTask,deleteTask}) => (
<div className='list-item'>
<p>{item.title}
<button className='button-edit'
onClick={()=> editTask(item,i)}>Edit </button>
<button className='button-delete'
onClick={()=> deleteTask(item,i)}>Delete </button>
</p>
</div>
));
var toggle = false;
const List= SortableContainer(({editTask,deleteTask}) => {
var items = data.map((item,i) => (
<ListItem
item={item}
index={i}
editTask={editTask}
deleteTask={deleteTask}
key={i}
/>
));
return (
<div>
{items}
</div>
);
});
class App extends React.Component {
constructor (props) {
super(props);
this.updateTask = this.updateTask.bind(this);
this.editTask = this.editTask.bind(this);
this.deleteTask = this.deleteTask.bind(this);
this.addTask = this.addTask.bind(this);
this.state = {
taskName:'',
data: [],
toggle: true
};
}
updateTask(e){
this.setState({taskName:e.target.value});
}
addTask(e){
e.preventDefault();
if(!this.state.taskName){
return;
}
data.push({
title: this.state.taskName
});
this.state.taskName='';
this.setState(this.state);
}
editTask(task,i){
this.state.taskName =task.title;
this.state.data.splice(i,1);
this.setState(this.state);
}
deleteTask(i){
data.splice(i,1);
this.setState(this.state);
}
onSortEnd = ({oldIndex, newIndex}) => {
this.setState({
data: arrayMove(this.state.data, oldIndex, newIndex),
});
};
render(){
return (
<div>
<h> To do List: </h>
<form onSubmit={this.addTask}>
<input type='text' placeholder='Task'
value={this.state.taskName}
onChange={this.updateTask} />
<input type='submit' className='buttonAdd' value='Add' />
</form>
<List
editTask={this.editTask}
deleteTask={this.deleteTask}
onSortEnd={this.onSortEnd} />
</div>
);
}
}
export default App;
Upvotes: 5
Views: 9797
Reputation: 4645
You can hide/show elements in react using conditional rendering.
Basically, you take advantage of the state and the fact that an update re-renders your component so you can render either a ListItem or an Input.
Here's an example I made : https://codesandbox.io/s/J6ynwlOq9 Tell me if you need an example with your code instead.
Upvotes: 0