User defined properties
In cases where you need to change (override) the properties of a component inside the form action or the component code in React, you can use userDefinedProps and setUserDefinedProps. It overwrites the properties that will go into the component, replacing the calculated properties as well as the default properties.
Overriding component properties using an action
Imagine that you need to upload a list of cities from the server to Dropdown once, when rendering the component. To do this, you need:
- Add Dropdown to the form, select it, and go to the Actions tab.
- Add a new Code action in the onDidMount event.
- Add the following code to the action editor and save:
/**
* @param {ActionEventArgs} e - the action arguments.
* @param {} args - the action parameters arguments.
*/
async function Action(e, args) {
const response = await fetch('https://gist.githubusercontent.com/rogargon/5534902/raw/434445021e155240ca78e378f10f70391dd594ea/countries.json')
const data = await response.json()
const preparedData = data.map(value => ({value, label: value}))
e.setUserDefinedProps({data: preparedData})
}
- Go to Preview and check it out. The list of countries is now loaded into Dropdown.
Overriding the properties of an arbitrary component
Inside the React component, you can use the useComponentData hook to access the userDefinedProps and setUserDefinedProps of the current component. You can consider its use using the example of the Tabs component implementation. You can also change the properties of another component. Here is an example:
import {useStore} from '@react-form-builder/core'
const MyComponent = () => {
const {componentTree} = useStore().form
const handleClick = () => {
const componentData = componentTree.findByKey('passwordInput')
if (componentData) {
const currentValue = componentData.userDefinedProps?.passwordMask ?? false
componentData.userDefinedProps ??= {}
componentData.userDefinedProps.passwordMask = !currentValue
}
}
return <button onClick={handleClick}>Toggle hide password</button>
}