How to scope field components based on record properties - react-admin

In react-admin, how do I access the record properties to show only certain components based on a record property value?
In the following code I want to only show the Bearer Token if the record name is not "All"; if the record name is "All", then only show if the user's role is "admin".
I'm getting "Uncaught TypeError: Cannot read property 'name' of undefined" in the OrgShow component, shown below, which I believe is saying that there is no "props". I've also tried "record" and "name", none of which are available.
export const OrgShow = ({ permissions, ...props }) => (
<Show permissions={permissions} title={<Title />} {...props}>
<SimpleShowLayout permissions={permissions}>
<TextField source="id" />
<TextField source="name" />
{
(props.record.name === 'All' && permissions === 'admin') || (props.record.name !== 'All' && permissions === 'user')
? <TextField source="bearer_token" />
: [
<FunctionField label='Bearer Token' render={record => obfuscator(record.bearer_token)} />,
<Alert severity="warning">You are not authorized for this org.</Alert>
]
}
</SimpleShowLayout>
</Show>
);
UPDATE:
I ended up solving this by using a FunctionField component, which I think is similar to user striped's solution; main difference being that FunctionField seems to be great for one-off function, whereas creating a new component seems appropriate if you're going to use that logic for more than one source. Anyway, here's the solution I came up with:
export const OrgShow = ({ permissions, ...props }) => (
<Show permissions={permissions} title={<Title />} {...props}>
<SimpleShowLayout permissions={permissions}>
<TextField source="id" />
<TextField source="name" />
<FunctionField permissions={permissions} label='Bearer Token' render={record => {
if ((record.name === 'All' && permissions === 'admin') || record.name !== 'All') {
return record.bearer_token
} else {
return obfuscator(record.bearer_token)
}
}} />
</SimpleShowLayout>
</Show>
);

I think that you need to create a specific component. The record should be automatically propagated to the child:
const MyComponent = (props) => {
return (props.record.name === 'All' && props.permissions === 'admin') || (props.record.name !== 'All' && props.permissions === 'user')
? <TextField source="bearer_token" record={props.record}/>
: [
<FunctionField label='Bearer Token' record={props.record} render={record => obfuscator(record.bearer_token)} />,
<Alert severity="warning">You are not authorized for this org.</Alert>
]
}
export const OrgShow = ({ permissions, ...props }) => (
<Show permissions={permissions} title={<Title />} {...props}>
<SimpleShowLayout permissions={permissions}>
<TextField source="id" />
<TextField source="name" />
<MyComponent permission={permissions} />
</SimpleShowLayout>
</Show>
);

Related

react-hook-form useFieldArray with React-Native

Is it possible to use ReactNative with useFieldArray from react-hook-form? I couldn't find any reference for that.
I'm trying to use it but I can't get the output data from the TextInputs. It looks like the onChange is not working, I tried to use the onChange prop but still couldn't make it.
Example:
const {
control,
formState: {errors},
register,
getValues,
handleSubmit,
} = useForm({
defaultValues: {
playerNameInput: [{playerName: ''}, {playerName: ''}],
},
});
const {fields, append, remove} = useFieldArray({
control,
name: 'playerNameInput',
});
return(
<>
{fields.map((player, index) => (
<View>
<Controller
control={control}
rules={{required: true}}
name="playerNameInput"
render={() => (
<TextInput
style={{width: 100}}
defaultValue={`${player.playerName}`}
{...register(`playerNameInput.${index}.playerName`)}
/>
)}
/>
</View>)}
<Button onPress={handleSubmit(data => console.log(data))}>
Save Changes
</Button>
</>
)

How to remove "No results found" label from the list when DataGrid has empty component

const TabbedDatagrid = (props: TabbedDatagridProps) => (
<Datagrid empty={<Empty />}>
<TextField source="id" />
<TextField source="createDate" />
</Datagrid>
);
const Empty = () => {
const { basePath } = useListContext();
return (
<Box textAlign="center" m={1}>
<Typography variant="h4" paragraph>
No products available
</Typography>
<Typography variant="body1">
Create one or import from a file
</Typography>
<CreateButton basePath={basePath} />
<Button>Import</Button>
</Box>
);
};
const MyList = (props: ListProps) => (
<List
{...props}
sort={{ field: 'createDate', order: 'DESC' }}
perPage={10}
filters={orderFilters}
pagination={<PostPagination />}
>
<TabbedDatagrid />
</List>
);
In the result both are displayed, 'No results found" and Empty component
How to display only Empty component?
The <Pagination> component takes a limit prop.
From the React-Admin docs
limit: An element that is displayed if there is no data to show (default: <PaginationLimit>)
You could try passing null <PostPagination limit={null} /> to hide that default "No results found" message.
You can replace these messages with your: Translating The Empty Page

Display Field in Edit Form

Currently, if I try to place a Field into an Edit form, the field doesn't display at all. There is no errors in the console or the terminal about why it wont.
Example:
<Edit undoable={false} {...props}>
<SimpleForm>
<FormRow>
<TextField source="id"/>
<TextField source="name"/>
</FormRow>
</SimpleForm>
</Edit>
will not display either of these on the page load, it will simply be blank.
Is there any way to use fields in the Edit form?
You need to pass in the record prop (and basePath if its a reference).
The Edit component does not get the record prop so create a form component and it will get passed the record as a prop
eg.
const ProjectEdit: FC<EditComponentProps> = props => {
const classes = useStyles();
return (
<RA.Edit {...props} title={<ProjectTitle />}>
<RA.SimpleForm>
<ProjectForm />
</RA.SimpleForm>
</RA.Edit>
);
};
export const ProjectForm = (props: any) => {
return (
<Box flex={1} mr={{ md: 0, lg: '1em' }}>
<RA.TextInput source="name" fullWidth={true} />
<Typography variant="h6" gutterBottom>
Tasks
</Typography>
<RA.TextField
source="name"
fullWidth={true}
record={props.record}
/>
<RA.ReferenceManyField
label="Tasks"
reference="Task"
target="projectId"
fullWidth={true}
record={props.record}
basePath="/Task"
>
<RA.SingleFieldList fullWidth={true}>
<RA.ChipField source="name" fullWidth={true} />
</RA.SingleFieldList>
</RA.ReferenceManyField>
</Box>
);
};

Unable to reset all the choices in SelectInput

The user needs to select a project in the AutocompleteInput first, doing that will set the filter property on the ReferenceInput which will load the possible values from the server into the SelectInput choices list. The data is fetched from the server however, if the choice that was selected in the SelectInput is no longer in the list, it is not reset. Furthermore the selected value is still in the choices list even though it was not returned from the rest service.
This is the code i wrote that has this issue:
<ReferenceInput label="Project" source="projectId" reference="projecten" filterToQuery={searchText => ({ naam: searchText })}>
<AutocompleteInput optionText="naam" optionValue="id" inputValueMatcher={() => null} />
</ReferenceInput>
<FormDataConsumer>
{({ formData, ...rest }) => {
return <ReferenceInput label="Lot" source="lotId" reference="loten" filter={{ projectId: formData.projectId }} {...rest}>
<SelectInput optionText="lotNummer"/>
</ReferenceInput>
}}
</FormDataConsumer>
How do I reset the SelectInput onChange of the AutocompleteInput and not load the currently selected value?
I know it's a late reply, but it might help someone. I achieved the same effect by using following steps on two SelectInputs inside a ReferenceInput each. I hope it works for your structure as well.
import change from redux-form
import { change } from redux-form
Give your SimpleForm a name
<SimpleForm form="myForm"...
Move your first ReferenceInput inside the FormDataConsumer
<FormDataConsumer>
{({ formData, ...rest }) => {
return (
<div>
<ReferenceInput label="Project" ...
<ReferenceInput label="Lot" ...
</div>
);
}
</FormDataConsumer>
Add an onChange to your first ReferenceInput
<ReferenceInput
label="Project" source="projectId" reference="projecten"
filterToQuery={searchText => ({ naam: searchText })}
onChange={() => {rest.dispatch(change('myForm', 'lotId', ''))}} >
Add a key property to your second ReferenceInput and use your first ReferenceInput's source as it's value
<ReferenceInput label="Lot" source="lotId"
reference="loten" filter={{ projectId: formData.projectId }}
key={formData.projectId} {...rest}>
Finally you'll get
<SimpleForm name="myForm">
<FormDataConsumer>
{({ formData, ...rest }) => {
return (
<div>
<ReferenceInput label="Project" source="projectId"
reference="projecten"
filterToQuery={searchText => ({ naam: searchText })}
onChange={() => {rest.dispatch(change('myForm', 'lotId', ''))}} >
<AutocompleteInput optionText="naam" optionValue="id"
inputValueMatcher={() => null} />
</ReferenceInput>
<ReferenceInput label="Lot" source="lotId" reference="loten"
filter={{ projectId: formData.projectId }}
key={formData.projectId} {...rest} >
<SelectInput optionText="lotNummer" />
</ReferenceInput>
</div>
);
}}
</FormDataConsumer>
</SimpleForm>
I used the steps from this link and added the key property according to another SO question but I'm unable to find it now.

How do you conditionally show fields in "Show" component in react-admin?

Some fields I want to only show if they have a value. I would expect to do this like so:
<Show {...props} >
<SimpleShowLayout>
{ props.record.id ? <TextField source="id" />: null }
</SimpleShowLayout>
</Show>
But that doesn't work. I can make it somewhat work by making each field a higher order component, but I wanted to do something cleaner. Here's the HOC method I have:
const exists = WrappedComponent => props => props.record[props.source] ?
<WrappedComponent {...props} />: null;
const ExistsTextField = exists(TextField);
// then in the component:
<Show {...props} >
<SimpleShowLayout>
<ExistsTextField source="id" />
</SimpleShowLayout>
</Show>
This correctly shows the value, but strips the label.
We need to update our documentation about this. In the mean time, you can find informations about how to achieve that in the upgrade guide: https://github.com/marmelab/react-admin/blob/master/UPGRADE.md#aor-dependent-input-was-removed
Here's an example:
import { ShowController, ShowView, SimpleShowLayout, TextField } from 'react-admin';
const UserShow = props => (
<ShowController {...props}>
{controllerProps =>
<ShowView {...props} {...controllerProps}>
<SimpleShowLayout>
<TextField source="username" />
{controllerProps.record && controllerProps.record.hasEmail &&
<TextField source="email" />
}
</SimpleShowLayout>
</ShowView>
}
</ShowController>
);
Maybe this way can be useful
import { FormDataConsumer } from 'react-admin'
<FormDataConsumer>
{
({ formData, ...rest}) => formData.id &&
<>
<ExistsTextField source="id" />
</>
}
</FormDataConsumer>