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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With