Yurrili
Yurrili

Reputation: 338

How to change element of list after clicking on it

I'm new to reactJS, and to react-native. I need advice. I'm having hard time with understanding how to create working action of element of a list.

So. I have parent component which creates tasks in scrollView.

        <ScrollView>
          {this.state.tasks.map(function(ele) {
            return (
              <Task
                action={this.handler}
                key={ele.id}
                title={ele.title}
                subtitle={ele.subtitle}
                state={ele.state}
              />
            );
          })}
        </ScrollView>

My parent component has state with variable tasks define in constructor.

this.state = {
    tasks: [
    { title: "A1", subtitle: "xyz", state: 0, id: 0 },
    { title: "A2", subtitle: "zyx", state: 0, id: 1 }]
}

And I want to change state to 1 if specific Task is clicked. I've tried to achived by doing sth like here: https://ourcodeworld.com/articles/read/409/how-to-update-parent-state-from-child-component-in-react But this is not working.

Upvotes: 0

Views: 81

Answers (2)

jlaitio
jlaitio

Reputation: 1948

You didn't provide much context, but basically it should be enough to give the id of your specific task in the handler call, either by providing it at the lower Task component level, or binding it when you're creating the element (by doing something like:

action={this.handler.bind(this, ele.id)}

, after which calling handler() at the Task level already contains the correct id.

Then in your handler method you have the id at hand, and can then modify the proper task in your state. This is a bit annoying to do in a clean way - you have to take the old task lists and create a new list with the proper task modified. After that you can modify the state with this.setState(newTaskList).

Upvotes: 0

Dev
Dev

Reputation: 3932

From what I have understood, you want to update the 'state' property in your tasks for particular task. In your handler, you could do something like this :

handler(ele) {
  let updatedTasks = this.state.tasks.map((task)=> {
     if(ele.id === task.id) {
        return Object.assign({}, task, {
          state: 1
        });
      } else {
        return task;
      }
   })

  //Set the new state
  this.setState({
     tasks: updatedTasks
  })
}

In your ScrollView action should be :

 action={(ele) => this.handler(ele)}

Upvotes: 1

Related Questions