ReactJS and file input Tag

In HTML, an <input type=”file”> lets the user choose one or more files from their device storage to be uploaded to a server or manipulated by JavaScript via the File API.

<input type=”file” />

Because its value is read-only, it is an uncontrolled component in React. It is discussed together with other uncontrolled components later in the documentation.

Handling Multiple Inputs

When you need to handle multiple controlled input elements, you can add a name attribute to each element and let the handler function choose what to do based on the value of event.target.name.

For example:

class Reservation extends React.Component {

constructor(props) {

super(props);

this.state = {

isGoing: true,

numberOfGuests: 2

};

this.handleInputChange = this.handleInputChange.bind(this);

}

handleInputChange(event) {

const target = event.target;

const value = target.type === ‘checkbox’ ? target.checked : target.value;

const name = target.name;

this.setState({

[name]: value

});

}

render() {

return (

<form>

<label>

Is going:

<input

name=”isGoing”

type=”checkbox”

checked={this.state.isGoing}

onChange={this.handleInputChange} />

</label>

<br />

<label>

Number of guests:

<input

name=”numberOfGuests”

type=”number”

value={this.state.numberOfGuests}

onChange={this.handleInputChange} />

</label>

</form>

);

}

}

Note how we used the ES6 computed property name syntax to update the state key corresponding to the given input name:

this.setState({

[name]: value

});

It is equivalent to this ES5 code:

var partialState = {};

partialState[name] = value;

this.setState(partialState);

Also, since setState() automatically merges a partial state into the current state, we only needed to call it with the changed parts.

Controlled Input Null Value

Specifying the value prop on a controlled component prevents the user from changing the input unless you desire so. If you’ve specified a value but the input is still editable, you may have accidentally set value to undefined or null.

The following code demonstrates this. (The input is locked at first but becomes editable after a short delay.)

ReactDOM.render(<input value=”hi” />, mountNode);

setTimeout(function() {

ReactDOM.render(<input value={null} />, mountNode);

}, 1000);

 

2D and 3D Transformation
ReactJS and select Tag

Get industry recognized certification – Contact us

keyboard_arrow_up