Create a mutlple email field input in react.js - reactjs

I am new to react and would like to create an entry field where a user can enter multiple email address
So far, I have an email field
<TextValidator
id="email"
aria-label="email"
label="Email address used to register"
required
name="email"
value={this.state.email ? this.state.email : ""}
onChange={this.handleChange({
name: "email",
index: 0
}).bind(this)}
autoComplete="email"
margin="normal"
variant="outlined"
fullWidth
validators={["required", "isEmail"]}
errorMessages={[
"this field is required",
"email is not valid"
]}
/>
I would like either a way to enter multiple emails in the single field or maybe an add/remove button to do it.
This is want my input look like at the moment
Thanks for your help

Try React multi-email - this is exactly what you're looking for.
Here's a link to the online demo where you can check it out.
Hope this helped!

I think to achieve that, you will need a stateVariable that holds the current text being entered by the user which you keep checking to see if its a valid email or alternatively check if the next key entered is a space and if so, add it to an array of existing emails.
To display the entered emails, you will need to use an editable div and a separate component that shows a single email, then loop through entered emails and display them as components inside the mail editable div
Something like
<EditableDiv>
{ email in emails
<Email email >
}
<CurrentEntry {EmailBeingEntered} />
</EditableDiv>
The above ain't really react but just an overview of what it might look like

A simple react component to format multiple email as the user types.
Simple code
No dependency
Small size
Simple customization
demo
https://codesandbox.io/s/jpvjk8m5o9
https://www.npmjs.com/package/react-multi-email

Related

Set maximum form field length in React Admin

Is there some way to set a field in a SimpleForm within React-Admin to limit the number of characters a user can type into that field?
Based on the docs, the React-Admin framework itself does not appear to contain this functionality. There is validation functionality to show an error when the user types too many characters, but apparently no built-in way to limit the number of characters typed. Given this, has anyone achieved this via other means?
For example, say the valid values for a 'Status' field are only 'A', 'B' or 'C'. How, while using React-Admin, would you limit that form field to accept only 1 character?
This is not strictly related to react-admin, but here you go:
// react-admin / MUI
<NumberInput inputProps={{ maxLength: 1 }} source="my_source" />
//HTML
<input type="number" maxLength=1 />

add placeholder to input in react js

I have an input field, in which I want to add in the placeholder ' tonnes' when the user enters a number. So this is what I came up with for that:
<input tabIndex={isBig ? "0" : "-1" } placeholder="in tonnes" value={plantDetail.co2ReleasedPerYear + ' tonnes'} onChange={(e) => setCO2(e.target.value)} className="specify-detail-inp"/>
But this adds in tonnes after each character. For example, if the user wants to enter 99, it shows up as '9 tonnes9 tonnes', whereas I want it to show up as '99 tonnes'. How can I fix this? I also tried slicing the text from the end as mentioned here -> Is there a way in react native to have a permanent placeholder inside of a text input?, but it didn't work.
Changing from
onChange={(e) => setCO2(e.target.value)}
To
onChange={(e) => setCO2(e.target.value.replace(' tonnes', ''))}
Could be one way to solve the problem, however i don't think its the best way. Best way in my honest opinion, would be to just have (tonnes) written in input label.

why state updates on second time clicking in react js

I have a state which fills by name of empty form inputs. first time when you click on button it fills by some key but it is empty at all but in second time it fills by some key like "age" or other thing. Do anyone face with this kind of problem?
Check if this works:
<input value={age} onChange={(e)=>setAge(e.target.value)} />
or
setAge(()=>newValue);
if not, please share some code.

Test input without label with React Testing Library

I use react-testing-library in my application. Normally, to check if the input is in the form, we use getByLabelText. For example:
getByLabelText(/name/i)
But what if my input does not have any label? This is because of the design (UI) so I cannot have a label for the input. How can I check if that input exists in the form?
You can use the following to target a text input field.
getByRole('textbox', {name: /name/i})
More info https://testing-library.com/docs/queries/about#priority
You can also add an aria-label to your input:
<TextField inputProps={{'aria-label': "example" }} />
and then in your test:
expect(screen.getByRole("textbox", { name: "example"})).toBeInTheDocument();
If you don't know an expected text in your input, you can add "data-testid" to your input and find it like that:
<input data-testid="my-input"/>
const myInput = getByTestId('my-input');
You could add a test ID to the input that solely will be used for testing purposes.
<input data-testid="your-id" />
And in your test you would do a query rather than get as get will fail the test if the element doesn't exist at all.
expect(queryByTestId('your-id')).toBeInTheDocument()
Or you could search by display value to look for the input value
expect(queryByDisplayValue('input-value')).toBeInTheDocument()

Material UI - Replicating the "required" text field error message

I have a simple TextField component from Material UI in React (notice the "required")
<TextField
label="Last name"
name="lastName"
required
value={this.state.lastName}
onChange={this.handleChange}
/>
I love the functionality and appearance of the "required" property. It looks like this when it's activated:
Unfortunately, this property is only available on their TextField component and not the RadioGroup or Select components. If I can at least replicate the appearance (and maybe the fact that it scrolls the page to the location of the input), I can apply it to all of my inputs for a consistent UI.
Does anyone know where they are getting the appearance from? It looks like it may be from a different package. Any help in finding it would be appreciated.
If you are referring to the "Please fill out this field" it looks like this might be a browser specific feature rather than a Material feature... Have you checked other browsers to see if this behaviour is reproducible?
Actually is fairly easy to change the styles for the errors that the different browsers show whenever a form is validated. Here your friend is the Constraint API.
There is an invalid event that will be fired before a form is submitted that checks if the elements that have the required attribute satisfy or not its constrains .
What I normally do is to use the onInvalid event handler and pass a callback where you can get a lot of info about the validation.
For example in event.target.validationMessage you'll see the "Please fill out this field" or the event.target.validity.valid will tell you if the element is valid or not. Bear in mind that you have to preventDefault the event.
e.preventDefault();
setInvalid( e.target.validity.valid );
setMessage( e.target.validationMessage );
This is how I've styled the native HTML errors using the <SnackbarContent /> component from material-ui.
Also, just to mention that CSS has a couple of pseudo elements that will help you to style the input. :invalid and :valid but this has nothing to do with the message itself.
Because this styles inconsistency really bugged me a time ago I created a npm plugin that deals with this for you, pretty-form-error it works with React and at least Angular 1.x.x
This is actually a property of input from vanilla html. Textfield is composed of smaller components and Input is one of the components they use. The required property will trigger the dialog to appear.
<html>
<body>
<form>
Username: <input type="text" name="username" required>
<input type="submit">
</form>
</body>
</html>
This snippet will also produce the same message.

Resources