Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unable add required attribute to a ReactJS input component

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?

like image 660
sfmaysf Avatar asked Jun 05 '17 00:06

sfmaysf


People also ask

How do you make the input field required in React?

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.

Can you conditionally add attributes to components in React?

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.

How do I add a required field in material UI?

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.


1 Answers

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.
  • You don't need to declare the 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. enter image description here

like image 87
Dan Avatar answered Sep 17 '22 00:09

Dan