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

Solution 1:

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.

Solution 2:

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.

Solution 3:

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

Solution 4:

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>