I am attempting to add a required attribute to a react input component:
export default function UiInput() {
render() {
return (
<input
{...customAttributes}
size={size ? size : null}
value={inputValue}
maxLength={maxLength}
required={required}
/>
)
and when I am calling my component like so,
<UiInput
required={required}
/>
I am not getting the red asterisk to render - not getting any errors when I pass in required to an input component, but no red asterisk is showing up, how can I make sure the asterisk renders for required inputs? Does ReactJS not support this?
fieldName — name of the field. required — You can use this property to set whether the input field is required or not. We can add logic in our react components that check whether we should make use of required input field or not. requiredTxt — Error message that shows up when user doesn't add any input.
In React, adding attributes conditionally is frequently necessary. In React, it is pretty simple. React is sophisticated enough to skip through some properties if the value you supply is untruthful. This is helpful, mainly when adding numerous characteristics conditionally.
We can use TextField component in Material UI to show input textbox. import TextField from "@material-ui/core/TextField"; When using the TextField component, we can pass the required attribute to mark the component as required.
Remember that you are passing required
down as a prop
to UiInput
.
The pattern you're using for your Component is a Stateless Functional Component, when you do this:
props
gets passed through as a parameter. render()
method, just simply write your return statement.You can declare your Component like so:
function UiInput(props) {
return (
<input
size={props.size ? props.size : null}
required={props.required}
/>
)
}
And render it like so:
<UiInput required="required" />
You can see a JSFiddle here. Please be aware that I did remove some props
for the purpose of this demo.
Here's the Component rendered, please ignore the data-reactroot
attribute.
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