I'm currently learning React and am following this guy Youtube Videos.
However, they are outdated and it's difficult to get along with the old codes. I already tried some Stackoverflow and Google solutions, but they didn't help.
Right now am I struggling on how I can access my variable todo
which I declared inside render()
and update it with a my function handleDelete
outside of render()
?
My goal is to delete the item i clicked on.
I already tried to set my variable inside constructor() but then it wasn't possible to give it the value of this.props.todos.
My code:
import React from 'react';
import ReactDom from 'react-dom';
export default class TodoItem extends React.Component {
handleDelete(item){
let updatedTodos = this.props.todos;
updatedTodos = updatedTodos.filter((val,index) => {
return item !== val;
})
todos = updatedTodos;
};
render() {
//Add all this.props items
let todos = this.props.todos;
todos = todos.map((item, index) => {
return (
<li>
<div className="todo-item">
<span className="item-name">{item}</span>
<span className="item-remove" onClick={this.handleDelete.bind(this, item)}> x </span>
</div>
</li>);
});
return (<React.Fragment>{todos}</React.Fragment>)
};
}
(This code is later exported to index.js where it is transpiled with Babel)
Thanks for your time taken!
Update:
Here is index.js
:
import React from 'react';
import ReactDom from 'react-dom';
import TodoItem from './todoItem';
class TodoComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
todos: ["clean up", "walk doggo", "take nap"]
};
}
render() {
return (<div>
<h1>The todo list:</h1>
<ul>
<TodoItem todos={this.state.todos}/>
</ul>
</div>);
}
}
ReactDom.render(<TodoComponent/>, document.querySelector(".todo-wrapper"));
todos
as a prop so it should be in a parent component's state. Liketodos
you need adelete
handler from your parent component as a prop. Then you will use this function in yourhandleDelete
function and pass thetodos
. Can we see your parent component as well? – devserkanreturn
belongs torender
. First one is formap
. So, actually it should work. – devserkan