Reputation: 1123
I have a react component with an uncontrolled input element like below:
class TestComponent {
onAddTypeClicked = el => {
console.log(el);
console.log(el.value);
};
render() {
return (
<div>
<input
name="asset_types"
ref={el => this.assetTypesAdd = el}
/>
<button
type="button"
onClick={e => this.onAddTypeClicked(this.assetTypesAdd)}
/>
</div>
);
}
Now when I type some value in input field and click button, the input is getting printed correctly but it's value is empty. It works fine if I use document.getElementById approach though. Can anyone point if I'm doing anything wrong, please?
Upvotes: 0
Views: 2674
Reputation: 1442
I believe your code is working correctly and the value of accessible in this.assetTypesAdd.value
and its printed value is the same. I'm not sure where you are getting an empty value for the input.
// Example class component
class MyComponent extends React.Component {
onAddTypeClicked = el => {
console.log(el.value);
this.forceUpdate();
};
render() {
return (
<div>
<input
name="asset_types"
ref={el => this.assetTypesAdd = el}
/>
<button
type="button"
onClick={e => this.onAddTypeClicked(this.assetTypesAdd)}
>
Click me
</button>
{this.assetTypesAdd &&
<div>Value of input: {this.assetTypesAdd.value}</div>}
</div>
);
}
}
// Render it
ReactDOM.render(
<MyComponent/>,
document.getElementById("react")
);
button {
width: 100px;
height: 20px;
display: block;
margin: 10px 0;
}
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
Upvotes: 1