alar
alar

Reputation: 207

Props value is returning undefined

I'm trying to get the value on input change but the value is undefined every time when I'm typing numbers

const Numbers = ({ onChange, value }) => {
    <Input 
    onChange={onChange}
    />
};

Numbers.propTypes= {
    value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
    onChange: PropTypes.func.isRequired
};
Numbers.defaultProps {
    value: undefined
}
export default Numbers;
class UseNumbers extends React.Component {
    state={
        value: this.props.value
    };

    onChange = (name, value) => {
        console.log('value on change', value);
        this.setState({ value });
    };

    render() {
        return (
            <Number
                {...this.props}
                onChange={
                    this.onChange
                }
            />
        );
    }
    
}

UseNumbers.propTypes = {
    value: PropTypes.oneOfType([PropTypes.number, PropTypes.string])
};

UseNumbers.defaultProps = {
    value: undefined
};

export default UseNumbers;

I tried to log the value and here is undefined. In the Number function, I have put props value and onChange as well and seems to be ok, but I do not figure it out why the value is undefined

Upvotes: 1

Views: 906

Answers (2)

Yousaf
Yousaf

Reputation: 29282

onChange event handler is passed an Event object instead of name and value that you are expecting.

You could extract the name and value from the Event object using Event.target property. Event.target.name will contain the name of the input which triggered the onChange event and Event.target.value will the the latest value of that input.

Although react passes Synthetic Event object to event handlers, instead of just Event object, synthetic event object is a cross-browser wrapper around the browser’s native event and has the same interface as the browser’s native event.

Change your event handler as shown below:

onChange = (event) => {
    // destructure name and value properties from event.target object
    const { name, value } = event.target;
    console.log('value on change', value);
    this.setState({ value });
};

P.S. You also need to add name attribute on the input element if you want to access the name of the input element which triggered the onChange event.

Upvotes: 3

rayn ma
rayn ma

Reputation: 21

your Numbers Component returns undefined,you sure your code works correctly? no error thrown?

const Numbers = ({ onChange, value }) => {
    return <Input 
    onChange={onChange}
    />
};

the point is you onChange function:

onChange = (e) => {
    console.log('value on change', e.target.value);
    this.setState({value});
}

input element passed Event as first parameter to onChange function, however, you mean this Input component is your custom component?

Upvotes: 0

Related Questions