diff --git a/.gitignore b/.gitignore index e39312d..69b1d40 100644 --- a/.gitignore +++ b/.gitignore @@ -19,6 +19,3 @@ npm-debug.log* yarn-debug.log* yarn-error.log* -# Remote Content -/docs/**/examples/**/*.md -/docs/**/examples/**/*.png diff --git a/docs/developer-documentation/examples-and-templates/examples/computed-form-fields.md b/docs/developer-documentation/examples-and-templates/examples/computed-form-fields.md new file mode 100644 index 0000000..c07f4cc --- /dev/null +++ b/docs/developer-documentation/examples-and-templates/examples/computed-form-fields.md @@ -0,0 +1,134 @@ +--- +description: Automatically calculates a read-only field in forms +title: Computed Form Fields +id: computed-form-fields +--- + +# Computed Form Fields Example + +This example shows you how to build a form with computed form fields. Computed form fields automatically calculate a value based on a separate read-only field. For example, if a user inputs a quantity, a computed form field can multiply that number by a price to give a total cost. + +Learn more about RADFish examples at the official [documentation](https://nmfs-radfish.github.io/radfish/developer-documentation/examples-and-templates#examples). Refer to the [RADFish GitHub repo](https://nmfs-radfish.github.io/radfish/) for more information and code samples. + +## Preview +This example will render as shown in this screenshot: + + + +## Steps + +### 1. Define Constants for Input Fields + +Before building out your form, define constants for each input field. Using constants helps reduce errors and makes your logic more maintainable. + +```jsx +const SPECIES = "species"; +const NUMBER_OF_FISH = "numberOfFish"; +const COMPUTED_PRICE = "computedPrice"; +``` + +In this example, we will build a form with three inputs. The values from the first two inputs will compute the value of `computedPrice`. + +### 2. Initialize the Form Component with State + +Next, we'll define the main form component. To manage the data entered in the form, we initialize it with a `formData` state variable, which is an empty object. This state will dynamically store the values of the form fields as users interact with the form. + +The `setFormData` function allows us to update the state whenever an input changes. This ensures the form data is kept in sync. + +```jsx +const ComputedForm = () => { + const [formData, setFormData] = useState({}); + + return ( + // form JSX will go here + ); +}; +``` + +### 3. Structuring the Form with Inputs + +In the `return` statement of the component, use the Trussworks `Form` component to structure your form. Within the form, include input components such as `TextInput`, referencing the variables defined in Step 1 (e.g. `NUMBER_OF_FISH`) instead of hardcoding strings. This practice helps avoid typos and ensures consistency when accessing the `formData` state. For better organization and styling, wrap your inputs within the `FormGroup` component provided by Trussworks. + +```jsx +return ( +