Reputation: 13
In the Grommet FormField
documentation, it states under Component;
The component may be custom as long it supports the properties of name, value, onChange (event => {}), while event has either event.value or event.target.value.
I'd like to implement a custom component but don't understand how it needs to interact with a controlled Form
component to supply its value
property. Is there an example somewhere that shows how to implement a custom component in a FormField
?
Upvotes: 1
Views: 864
Reputation: 1218
Here is a code example of Controlled Form that is using a custom input component. I used a plain input tag since it supports the docs specification as mentioned above
...it supports the properties of name, value, onChange (event => {}), while event has either event.value or event.target.value.
However, you can feel free to use your own input component implementation using the template example below. The value of the input will be communicated to the controlled Form without extra coding. Run the following and check out the console logs to see how the value is being updated as you type in the custom input.
import React, { useState } from "react";
import { render } from "react-dom";
import { Box, Button, Form, FormField, Grommet, TextInput } from "grommet";
import { grommet } from "grommet/themes";
const defaultValue = {
name: "",
custom: ""
};
export const App = () => {
const [value, setValue] = useState(defaultValue);
return (
<Grommet full theme={grommet}>
<Box fill align="center" justify="center">
<Box width="medium">
<Form
value={value}
onChange={(nextValue, { touched }) => {
console.log("Change", nextValue, touched);
setValue(nextValue);
}}
onSubmit={(event) =>
console.log("Submit", event.value, event.touched)
}
>
<FormField label="TextInput Field" name="name">
<TextInput name="name" />
</FormField>
<FormField
label="Custom Component Field"
name="custom"
component={(props) => <input {...props} />} // custom component
/>
<Box direction="row" justify="between" margin={{ top: "medium" }}>
<Button type="submit" label="Update" primary />
</Box>
</Form>
</Box>
</Box>
</Grommet>
);
};
render(<App />, document.getElementById("root"));
Upvotes: 1