Chandrahas Balleda
Chandrahas Balleda

Reputation: 2822

A Query on lists in React

I am a beginner in React and have a basic query. See the below code, where I wanted to print the index of array on the browser console when any person's name get clicked.

App.js

import React, { Component } from 'react';
import './App.css';
import Para from './Para/Para';


class App extends Component {

state = {
  persons : ['Max', 'Nick', 'Peter']
}

clickHandler= (index) =>{
  console.log(`CLICKED ${index}`);
}


  render() {

    var members = [];
    this.state.persons.forEach((element,index)=>{
      members.push(<Para clicked= {this.clickHandler.bind(this,index)} name={element} key={element}></Para>);
    })

    return (
     <div>
      {members}
     </div>
    );

  }
}
export default App;

Functional Component - Para.js

import React from 'react';

const para = (props) =>{
   return( <p onClick = {props.clicked}>{props.name}</p>)
}

export default para;

I am receiving output as expected. My query here is that how react is able to find the index of the person's name in array when get clicked? Because when page gets loaded, all the components got rendered and when the element (person's name) get's clicked, does react re-render this functional component to find the index..? What is actually happening behind the scenes? Thanks in advance.

Upvotes: 0

Views: 729

Answers (2)

Aprillion
Aprillion

Reputation: 22322

for explanation how it works, this.clickHandler.bind(this,index) returns a partially applied function - logically equivalent to (...args) => clickHandler(index, ...args)


FWIW: onClick built-in prop for event handlers are always called with event as the first argument, so an idiomatic way how to pass other arguments is to use a factory / closure variable, e.g.:

makeClickHandler = (index) => (event) => { console.log(`CLICKED ${index}`) }
...<Para clicked={makeClickHandler(index)}...

this way it's explicit that you want to ignore the event argument of the clickHandler function (which is returned as an anonymous function by makeClickHandler())

Upvotes: 1

Slawomir Wozniak
Slawomir Wozniak

Reputation: 518

You loop through your array, and on every element you have an access to the index of it. (That's only JS feature, not React, check https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)

So you "assign" a function with a specific argument(index) as a prop. You're basically saying "This unique element, when clicked, runs clickHandler(1)". Another one "runs clickHandler(2)" etc.

And when you assigned multiple divs to the members, you render it. In your code nothing gets updated, because the state stays the same.

Upvotes: 1

Related Questions