Lahel Light
Lahel Light

Reputation: 66

How do I get props from a onChange() event?

I passed an onChange function into a react component along with another prop. In the onChange function I need to get the prop I passed into the component. How might I do that? I am thinking of using event.target but I don't know if props are returned from event.target.

Background: I am trying to make a basic ideaboard and right now just want to create several inputtable textboxes based on an array in a file. The component Idea represents a single idea, and it has two text input areas.

function Idea(props){
    return(
        <div>
            <p>Date: {props.date}</p>
            <input 
                type = "text"
                value = {props.title}
                name = "title"
                placeholder = "title"
                onChange = {props.handleChange}
                />

            <textarea
                type = "text"
                value = {props.content}
                name = "content"
                placeholder = "content"
                onChange = {props.handleChange}
                />
        </div>)}

A parent component Ideas stores as an array of objects in state the content of the textboxes. Each element in the array is an object representing the data of one Idea component, and stores date, title and content.

import ideasData from "./ideasData
class Ideas extends Component{
    constructor() {
        super()
        this.state = {
            ideas : ideasData
        }
        this.handleChange = this.handleChange.bind(this)
    }

A function in Ideas, handleChange is passed down as a prop to every Idea component rendered. It updates the array stored in Ideas's state. For example, if I typed "things" into a "title" textbox of the third idea, then ideas[2].title should become "things". However, this requires me to retrieve the "index" prop from the component as otherwise it wouldn't know which element of the array in state should be updated. "index" is a prop passed down into every Idea component.

    handleChange(event) {
        const {name,value} = event.target
        let index = ????????
        let curIdeas = this.state.ideas
        curIdeas[index][name] = value
        this.setState(curIdeas)
    }

Upvotes: 2

Views: 3384

Answers (1)

Vencovsky
Vencovsky

Reputation: 31713

When rendering the Ideas you need to pass the index as a prop.

this.state.ideas.map((idea, i) = > <Idea {...idea} index={i} />

Then inside Idea you call handleChange with the index coming from props.

onChange = {(e) => props.handleChange(e, this.props.index}

And get the index in the handleChange

handleChange(event, index) {
    const {name,value} = event.target
    let index = index
    let curIdeas = this.state.ideas
    curIdeas[index][name] = value
    this.setState(curIdeas)
}

Upvotes: 2

Related Questions