Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
32
rated 0 times [  36] [ 4]  / answers: 1 / hits: 26650  / 7 Years ago, thu, september 7, 2017, 12:00:00

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?


More From » reactjs

 Answers
54

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'/>




[#56550] Monday, September 4, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
loric

Total Points: 110
Total Questions: 96
Total Answers: 91

Location: Estonia
Member since Wed, Jun 8, 2022
2 Years ago
;