Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a text input non editable with React?

I searched for this and the closest thing I found was this SO post here; however, it does not use React.

I tried this syntax below which is inside a React component:

  <input 
    value={props.value}
    onChange={props.onChange} 
    className={props.className}
    placeholder={props.placeholder}
    name={props.name} {props.readonly && 'readonly'}>

but I get an eslint parsing error and when I check the UI it is still writable.

like image 358
user17791008 Avatar asked Oct 29 '25 16:10

user17791008


2 Answers

Remove {props.readonly && 'readonly'} and add readonly={props.readonly} Refer to here for the readonly attribute description.

Your problem is the input element (and all react components) only takes key/value pairs in the form of key={value}, but you are trying to insert a bit of javascript code without assigning the value of the result to a key.

Edit: should use readonly attribute, not disabled, as mentioned in the comments.

like image 76
Blake Avatar answered Oct 31 '25 07:10

Blake


Use the property readOnly and pass it a boolean

const Example = (props) => {
  return (    
      <input readOnly={props.readonly} value={props.title}/>   
  );
};

// Render it
ReactDOM.render(
  <Example title="Example using Hooks:" readonly={true}/>,
  document.getElementById("react")
);
[readonly] {color:red}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>
like image 34
charlietfl Avatar answered Oct 31 '25 05:10

charlietfl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!