A
A
Alexander2020-10-03 11:59:52
JavaScript
Alexander, 2020-10-03 11:59:52

Optional props passing to react?

Let's say there is some form, and in it the fields

<Input onNameChange={this.props.onNameChange} title={"Name"} type={'text'}/>
<Input title={"Surname"} type={'text'}/>

through onNameChange I pass the state up, while in the Input component:
<label>
                    <p>{this.props.title}</p>
                    <input onChange={this.handleChange} type={this.props.type}/>
 </label>

The problem is that I need to pass the change handler only to some fields, not to others, so it turns out that when I change the Surname field, I get an error. How can I make it so that the onChange of the input would be called when I pass the handler?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
turiq, 2020-10-03
@turiq

onChange =(name)=> this.props.onNameChange && this.props.onNameChange(name)

W
WbICHA, 2020-10-03
@WblCHA

You need to be onChange in андефайнд.
In a functional component, this problem does not even arise:

const Input = ({ title, type, onNameChange }) => (
  <label>
    <p>{title}</p>
    <input onChange={onNameChange} type={type} />
  </label>
)

PS: I hope I didn’t mess up anything, otherwise I rarely use React.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question