2

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.

user17791008
  • 247
  • 2
  • 12

4 Answers4

3

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.

Blake
  • 41
  • 2
2

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>
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • This is amazing how many solutions there are. This one appears the easiest and most consistent with the rest of my code. I'm surprised this was not the solution to the original link I posted. It seems more "standard" or "normalized". – user17791008 Jan 05 '22 at 02:59
1

You could have an input without the onChange when props.readonly is true. Something like this:

<input 
    value={props.value}
    onChange={props.readonly ? undefined : props.onChange} 
    className={props.className}
    placeholder={props.placeholder}
    name={props.name}
/>
Hanchen Jiang
  • 2,514
  • 2
  • 9
  • 20
  • Yeah a clear div could block from clicking on it, but user could still tab into it. You could also not let user tab into it, but that sometimes wouldn't be a great user experience. – Hanchen Jiang Jan 05 '22 at 02:30
1

The answer you used is non-normative.

Instead of using

 ... readonly>

use the more common HTML syntax as follows:

readonly='readonly'

and then pick one of the many ways to implement in react / JSX.

favor
  • 355
  • 2
  • 13