user10693340
user10693340

Reputation: 49

In React how does one pass an event handler as a prop while mapping through an array?

I know how to map through an array of objects, passing data from each object as props, to render an array of components but how does one pass an event handler during this process? The following code is my failed attempt:

class App extends React.Component {
    constructor() {
        super();
        this.state = {
            allObjects: arrayOfObjects //arrayOfObjects is simply an imported array of object data
        }
        this.handleChange = this.handleChange.bind(this);
    }

    handleChange() {
        console.log("test"); // I'm merely trying to console log for this example
    }

    render() {
        const objectsRendered = this.state.allObjects.map((i) => <myComponent key={i.id} i={i} onChange={this.handleChange}/>)

        return(
            <form>
                {objectsRendered}
            </form>
        )
    }
}

Here's the code for myComponent:

function myComponent (props) {
    return(
        <div>
           <input type="range" min="0" max="100" className="slider" id={props.i.id} onChange={props.handleChange}/>
        </div>
    )
}

Upvotes: 0

Views: 193

Answers (1)

victor.ja
victor.ja

Reputation: 888

The problem is you are passing a prop named onChange to <myComponent /> instead of one named handleChange

So you should do this instead:

function myComponent (props) {
    return(
        <div>
           <input type="range" min="0" max="100" className="slider" id={props.i.id} onChange={props.onChange}/>
        </div>
    )
}

—————————————

When you are passing a prop, the logic is similar to a variable declaration: left value is prop name, right value is the prop value you assign:

propName={propValue}

Upvotes: 3

Related Questions