Reputation:
I want to add or remove an attribute from an html input element.
What i'm done is this:
constructor(props) {
super(props);
this.state = {inputState: 'readOnly'};
}
And the render function:
<input className="form-control" type="text" value={floor} {...this.state.inputState} />
As you can see i want set the "readOnly" attribute on the input element. But now i get an error which says:
Unknown props
0
,1
,2
,3
,4
,5
,6
,7
on tag. Remove these props from the element
When an user is clicking on the input element it should become editable, so i want to dynamicly change this attribute.
But how can i do that?
Upvotes: 7
Views: 30356
Reputation: 104479
To control the mode of input
element define readOnly
attribute with it and control it's value by state variable, Whenever you update the state value react will re-render the component and it will change the mode on the basis of state value.
Check this example:
class App extends React.Component{
constructor(){
super();
this.state = {readOnly: true}
this._click = this._click.bind(this);
}
_click(){
this.setState(prevState => ({readOnly: !prevState.readOnly}))
}
render(){
return <div>
<input readOnly={this.state.readOnly}/>
<button onClick={this._click}>Toggle</button>
</div>
}
}
ReactDOM.render(<App/>, document.getElementById('app'))
<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>
<div id='app'/>
Upvotes: 9
Reputation: 24680
You can try this.
constructor(props) {
super(props);
this.state = {readOnly: true};
}
render() {
return (<input className="form-control" type="text" value={floor} readOnly={this.state.readOnly} />)
}
Upvotes: 0
Reputation: 1478
Try this instead:
this.state = { inputState: { readOnly: true }};
Upvotes: 0