React-Admin TextField and TextInput not showing label and css - javascript

In React-Admin when i move the child components to another component and try to render it inside the simpleform tag then textfields are not showing its value and textinput tag CSS also goes missing. what i am trying to do is to create a common component for the create and edit tag so i break it down it to multiple components and then try to render it using props.children
export const AssessmentEdit = props => {
return (
<CommonComponents {...props} componentType='edit' notif='Assessment Preference Updated successfully' redirect='list' validation={validateAssessment}>
<FormData {...props} componentType='edit'/>
</CommonComponents>
)
};
const CommonComponent = (props) => {
const notify = useNotify();
const redirect = useRedirect();
const onSuccess = () => {
notify(props.notif);
redirect(props.redirect, props.basePath);
};
const Compo = components[props.componentType];
console.log(props.componentType)
return (
<Compo {...props}
undoable={false}
onSuccess={onSuccess}>
{props.componentType === 'show' ? <SimpleShowLayout>
{props.children}
</SimpleShowLayout> : <SimpleForm
redirect={props.redirect}
validate={props.validation}>
{props.children}
</SimpleForm>}
</Compo>
);
};
export const FormData = (props) => {
const classes = utilStyles();
return (
<React.Fragment>
{props.componentType === 'edit' && <>
<TextField {...props} source="id" label="Id"/>
<TextField {...props} source="organization_id" label="Organization"/>
<TextField {...props} source="provider" label="Provider"/>
</>}
<TextInput source="name" label={'Name *'}/>
<SelectInput source="category"
label={'Category *'}
choices={AssessmentCategory}
optionText="name"
optionValue="value"/>
<ArrayInput source="topics">
<SimpleFormIterator>
<TextInput/>
</SimpleFormIterator>
</ArrayInput>
<TextInput source="description"
label={'Description *'}
className={classes.fullWidth}
options={{multiLine: true}}/>
<RichTextInput source="instructions"
label={'Instructions *'}/>
<NumberInput source="duration"
label={'Duration *'}/>
<BooleanInput source="randomize_questions"/>
<FormDataConsumer>
{({formData, formData: {randomize_questions}}) => {
if (randomize_questions) {
return <NumberInput source="question_count" label={'Question Count *'}/>
}
return null;
}}
</FormDataConsumer>
<ArrayInput source="questions"
label={'Questions *'}>
<SimpleFormIterator>
<ReferenceInput source="questionId"
className={classes.fullWidth}
label={"Question"}
reference="search-questions">
<AutocompleteInput optionValue="id"
matchSuggestion={() => true}
inputText={(value) => {
return value && value.question_text && value.question_text.slice(0, 200)
}}
className={classes.fullWidth}
optionText={<Custom/>}/>
</ReferenceInput>
<NumberInput label="Question Weight" source="question_weight"/>
</SimpleFormIterator>
</ArrayInput>
<ArrayInput source="skills" label={'Skills *'}>
<SimpleFormIterator>
<ReferenceInput source="skillId"
label={"Skill"}
className={classes.fullWidth}
reference="perform-skill-search">
<AutocompleteInput optionValue="id"
className={classes.fullWidth}
optionText="display_name"/>
</ReferenceInput>
<SelectInput label="Skill Level"
choices={levels}
optionText="key"
optionValue="value"
source="skill_level"/>
</SimpleFormIterator>
</ArrayInput>
</React.Fragment>
);
};

I ended up creating my own TextField component and explicitely passing down the props:
interface CustomTextFieldProps {
label?: string,
record?: Record,
source: string
}
const CustomTextField = (props: CustomTextFieldProps) => (
<Labeled label={props.label ? props.label : startCase(props.source)}>
<span>{get(props.record, props.source)}</span>
</Labeled>
);
Usage:
<CustomTextField source="fieldName" record={props.record} />

Related

list of ref shows undefined when logging

I've made a list of refs for each of my components that is being rendered in a map, I am assigning a ref to a button within EditWebAppTypeForm and am trying to use it within MappedAccordion but it shows undefined? what can I do to make sure ref is set before passing it in the MappedAccordion component?
The information logged in addtoRefs function is correct, it shows -
(2) [button, button]
I've removed a lot of the code so its easier to read.
function Admin() {
const allRefs = useRef([] as any);
allRefs.current = [];
const addtoRefs = (e: any) => {
if (e && !allRefs?.current?.includes(e)) {
allRefs?.current?.push(e);
}
console.log(allRefs.current); <-- Logs correct info
};
return (
<div className="adminContainer">
<Grid container spacing={2}>
<Grid item md={8} xs={12} sm={12}>
<div style={{ width: 725, paddingBottom: 150 }}>
{webAppTypes &&
webAppTypes.map((a: IWebAppType, index: number) => {
return (
<>
<Accordion
key={a.id}
defaultExpanded={a.id === 0 ? true : false}
>
<AccordionDetails>
<EditWebAppTypeForm
key={a.name}
setWebAppTypes={setWebAppTypes}
IWebAppTypeModel={a}
ref={addtoRefs} // <-- returning ref to add to list
/>
<MappedAccordion
waobj={a}
key={a.id}
setWebAppTypes={setWebAppTypes}
editRef={allRefs.current[index]} <-- using ref but showing undefined in MappedAccordion component
/>
</AccordionDetails>
</Accordion>
</>
);
})}
</div>
</Grid>
</Grid>
</div>
);
}
export default Admin;
EditWebAppTypeForm Component -
const EditWebAppTypeForm = (props: any, ref: any) => {
return (
<div className="editWebAppSContainer">
<form onSubmit={handleSubmit(onSubmit)} id="edit-app-form">
<button hidden={true} ref={ref} type="submit" /> // <-- Assiging ref to button
</form>
</div>
);
};
export default forwardRef(EditWebAppTypeForm);
type MappedAccordionProps = {
waobj: IWebAppType;
setWebAppTypes: Dispatch<SetStateAction<IWebAppType[]>>;
editRef: any;
};
function MappedAccordion({
waobj,
setWebAppTypes,
editRef,
}: MappedAccordionProps) {
const onSubmit = (data: FormFields) => {
console.log(editRef); // <-- Logs undefined
};
return (
<div>
<form onSubmit={handleSubmit(onSubmit)} id="environment-form">
</form>
</div>
);
}
export default MappedAccordion;
I would create an extra component WebAppTypeAccordion like this :
function WebAppTypeAccordion({a, setWebAppTypes}) {
const [formEl, setFormEl] = useState(null);
function handleRef(el) {
if (el) {
setFormEl(el)
}
}
return (
<Accordion defaultExpanded={a.id === 0}>
<AccordionDetails>
<EditWebAppTypeForm
setWebAppTypes={setWebAppTypes}
IWebAppTypeModel={a}
ref={handleRef}
/>
<MappedAccordion
waobj={a}
setWebAppTypes={setWebAppTypes}
editRef={formEl}
/>
</AccordionDetails>
</Accordion>
);
}
Then you can update the Admin component :
webAppTypes.map((a: IWebAppType) => (
<WebAppTypeAccordion key={a.id] a={a} setWebAppTypes={setWebAppTypes} />
))

Is rendering the Autocomplete options list with column headers possible?

I would like to know if it is possible to customise the above example so that the list would have column headers such as Title and duration. I have tried to see if I could get it to work using a custom ListBox, but no such luck. Below is a snippet of my own code:
const PopperMy = function (props: PopperProps) {
return <Popper {...props} style={{ width: 500 }} placement='bottom-start' />;
};
return (
<Autocomplete
filterOptions={(x) => x}
getOptionLabel={(option: Record<string, unknown>) => `${option.order}, ${option.name}, ${option.email}, ${option.phone}, ${option.location}`}
renderOption={(props, option: any) => {
return (
<li {...props} key={option.ID} >
Order: {option.order}, Name: {option.name}, Email: {option.email}, Phone: {option.phone}, Location: {option.location}, Status: {option.status}
</li>
);
}}
options={results}
value={selectedValue}
clearOnBlur={false}
freeSolo
PopperComponent={PopperMy}
disableClearable={true}
includeInputInList
onChange={(ev, newValue) => {
setSelectedValue(newValue);
}}
onInputChange={(ev, newInputValue) => {
setInputValue(newInputValue);
}}
renderInput={(params) => (
<TextField {...params} />
)} /> )
this is achievable by customizing the popper component. In your case, something like `
const PopperMy = function (props) {
const { children, ...rest } = props;
return (
<Popper {...rest} placement="bottom-start">
<Box display="flex" justifyContent="space-between" px="16px">
<Typography variant="h6">Title</Typography>
<Typography variant="h6">Year</Typography>
........... rest of the titles
</Box>
{props.children}
</Popper>
);
};
`
would work. Here is a working example i have created - https://codesandbox.io/s/heuristic-golick-4sv24u?file=/src/App.js:252-614

React TextField with collapse

How to hide the lists of cities when the textfield is empty and when the user start typing the lists will show.
https://codesandbox.io/s/loving-platform-t2cyb?file=/src/LocationWidget.js
const openSearch = () => {
setViewLocationList(true);
startSearch();
};
const stopSearch = () => {
setSearchParameter('')
setViewLocationList(false);
};
<TextField
variant="outlined"
placeholder="Search Locations"
onFocus={openSearch}
onChange={filterResults}
value={searchParameter}
classes={{notchedOutline:classes.input}}
InputProps={{
endAdornment: (
<IconButton onClick={stopSearch} edge="end">
<ClearIcon />
</IconButton>
),
classes:{notchedOutline:classes.noBorder},
startAdornment: (
<InputAdornment position="start">
<SearchIcon />
</InputAdornment>
),
}}
/>
</Box>
<Collapse in={viewLocationList} sx={{ my: '2px' }}>
<Box className="rounded-scrollbar widget-result-container">
{filteredLocations.map((location, index) => (
<LocationWidgetItem
key={index}
location={location}
onClickLocation={setActiveLocation}
/>
))}
</Box>
</Collapse>
You have to take state variable in which you have to store whatever user is typing:
const [text,setText] = useState("");
and in your filterLocations you have to update its value
const filterLocations = (txt) => {
setText(txt.target.value);
let filteredLocations = locations.filter((e) =>
e.name.toLowerCase().includes(txt.target.value.toLowerCase())
);
setSearchParameter(filteredLocations);
};
And Finally in your render, render ul conditioanlly
{ !!text && <ul>
{searchParameter.map((location) => (
<li key={location.name}>{location.name}</li>
))}
</ul>}
https://codesandbox.io/s/dreamy-roentgen-0jnoi?file=/src/LocationWidget.js
please find below code.
export default function LocationWidget({ locations }) {
const [searchParameter, setSearchParameter] = useState(locations);
const [inputText, setInputText] = useState(null);
const filterLocations = (txt) => {
setInputText(txt.target.value);
let filteredLocations = locations.filter((e) =>
e.name.toLowerCase().includes(txt.target.value.toLowerCase())
);
setSearchParameter(filteredLocations);
};
return (
<>
<input type="text" onChange={filterLocations} />
{inputText && <ul>
{searchParameter.map((location) => (
<li key={location.name}>{location.name}</li>
))}
</ul>}
</>
);
}
You'd like to set an 'input' eventListener on the input field. And check if the inputField length > 0, then set the setViewLocationList(true); and if the inputField length === 0, then set the setViewLocationList(false).

React Autocomplete with Material UI

I'm implementing a component Autocomplete using Material UI library.
But there's a problem - I'm not sure how to pass value and onChange properly, because I have a custom implementation of TextField that requires value and onChange as well. Should I pass value and onChange twice - to Autocomplete and TextField? Or maybe there's a better solution? Would appreciate any help!
Here's my code:
import { Autocomplete as MuiAutocomplete } from '#material-ui/lab'
import { FormControl } from 'components/_helpers/FormControl'
import { useStyles } from 'components/Select/styles'
import { Props as TextFieldProps, TextField } from 'components/TextField'
export type Props = Omit<TextFieldProps, 'children'> & {
options: Array<any>
value: string
onChange: (value: string) => void
disabled?: boolean
}
export const Autocomplete = (props: Props) => {
const classes = useStyles()
return (
<FormControl
label={props.label}
error={props.error}
helperText={props.helperText}
>
<MuiAutocomplete
options={props.options}
// value={props.value}
// onChange={event =>
// props.onChange((event.target as HTMLInputElement).value as string)
// }
classes={{
option: classes.menuItem,
}}
disabled={props.disabled}
getOptionLabel={option => option.label}
renderInput={params => (
<TextField
{...params}
placeholder={props.placeholder}
value={props.value}
onChange={props.onChange}
/>
)}
renderOption={option => {
return <Typography>{option.label}</Typography>
}}
/>
</FormControl>
)
}```
Material UI has props built in to handle the state of the Autocomplete vs input values.
You can see it in use in the docs here: https://material-ui.com/components/autocomplete/#controllable-states
In your example, you would want to add the inputChange and onInputChange props to the Autocomplete component. These will get passed down to your TextField through the params passed to the renderInput function.
So your final code would look something like the below snippet copied from the linked documentation:
<Autocomplete
value={value}
onChange={(event, newValue) => {
setValue(newValue);
}}
inputValue={inputValue}
onInputChange={(event, newInputValue) => {
setInputValue(newInputValue);
}}
id="controllable-states-demo"
options={options}
style={{ width: 300 }}
renderInput={(params) => <TextField {...params} label="Controllable" variant="outlined" />}
/>
import React, { useEffect, useState } from "react";
import { Autocomplete } from "#mui/material/node";
import { Controller, useFormContext } from "react-hook-form";
import { TextField } from "#mui/material";
import PropTypes from "prop-types";
const valueFunc = (arr, id) => {
const temp = arr.length > 0 && arr?.find((element) => element.id === id);
return temp;
};
AutocompleteSearch.propTypes = {
options: PropTypes.arrayOf({
title: PropTypes.string,
id: PropTypes.string,
}),
name: PropTypes.string,
};
export default function AutocompleteSearch({
name,
options,
label,
id,
...other
}) {
const [temp, setTemp] = useState({});
const { control, setValue } = useFormContext();
useEffect(async () => {
const found = valueFunc(options, id);
await setTemp(found);
}, [options, id]);
return (
<Controller
control={control}
name={name}
rules={{ required: true }}
render={({ fieldState: { error } }) => (
<>
<div >
<Autocomplete
id="controllable-states-demo"
onChange={(_, v) => {
setValue(name, v?.id);
setTemp(v);
}}
onBlur={(e) => {
e.target.value == "" && setValue(name, "");
}}
value={temp}
options={options}
getOptionLabel={(item) => (item.title ? item.title : "")}
renderInput={(params) => (
<>
<TextField
{...params}
label={label}
InputLabelProps={{
style: {
fontSize: "14px",
fontWeight: "400",
color: "#FF5B00",
},
}}
size="small"
error={temp === null && !!error}
helperText={temp === null && error?.message}
{...other}
/>
</>
)}
/>
</div>
</>
)}
/>
);
}
<AutocompleteSearch
name="pharmacy_group_title"
label="Pharmacy Group"
options={pharmacyGroups} // Array {id , title}
id={defaultValues?.pharmacy_group_title} // ID
/>

React native typeScript and forwardRef in a functional component

I'm in react native app an I use typeScript too.
I have a functional component :
const Input: React.FunctionComponent<IInputProps> = ({
inputStyle,
placeHolderColor = EAppColors.DARK_GREY,
placeHolder,
value,
onChangeText,
autoFocus,
onFocus,
onBlur,
onSubmitEditing,
ref,
keyboardType = EKeyboardType.DEFAULT,
}) => {
return (
<StyledInput
testID="TextInputID"
placeholderTextColor={placeHolderColor}
placeholder={placeHolder}
...
I create some ref for different input before my render:
const firstNameRef = React.createRef<TextInput>();
const lastNameRef = React.createRef<TextInput>();
const birthDateRef = React.createRef<TextInput>();
and I use after this component in a class like that :
<StyledTextInput
label={I18n.t('auth.heading.firstNameLabel')}
errorText={errorText}
ref={firstNameRef}
autoFocus={true}
placeHolder={I18n.t('auth.placeHolder.firstName')}
isFocused={focusOnFirstFields}
hasError={hasError}
onFocus={() => this.setState({ focusOnFirstFields: true })}
onBlur={() => this.setState({ focusOnFirstFields: false })}
showClearButton={showFirstClearButton}
value={firstName}
onClearText={() => this.onClearText(1)}
onChangeText={(value: string) =>
this.setState({
firstName: value,
disabled: false,
showFirstClearButton: true,
})
}
onSubmitEditing={() => {
if (lastNameRef !== null && lastNameRef.current !== null) {
lastNameRef.current.focus();
}
}}
keyboardType={EKeyboardType.DEFAULT}
/>
But when I want to use onSubmitEditing for focus the next input, I have this error :
How can I resolve this issue ?
Thank You!
Like this:
const FancyButton = React.forwardRef</* type of ref*/HTMLButtonElement, /* component props */ComponentProps>((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>))
It will be correctly typed as
const FancyButton: React.ForwardRefExoticComponent<React.RefAttributes<HTMLButtonElement>>
(You don't need to use React.FunctionComponent when using forwardRef).
const Input = React.forwardRef<TextInput, IInputProps>(({
inputStyle,
placeHolderColor = EAppColors.DARK_GREY,
placeHolder,
value,
onChangeText,
autoFocus,
onFocus,
onBlur,
onSubmitEditing,
keyboardType = EKeyboardType.DEFAULT,
}, ref /* <--- ref is passed here!!*/) => {
// assuming this is a TextInput
return (
<StyledInput
ref={ref}
testID="TextInputID"
placeholderTextColor={placeHolderColor}
placeholder={placeHolder}
...
})
I faced a similar problem a few months ago. I solved it by doing:
import {TextInputProps, TextInput} from 'react-native';
type IProps = TextInputProps & {
labelText?: string;
};
const TextInputStd: React.FC<IProps> = React.forwardRef(
(
{
labelText,
...textInputProps
}: IProps,
ref: React.Ref<TextInput>,
) => {
const {styles} = useStyles(_styles);
return (
<>
<View style={[styles.textInputContainer, styles2.textInputContainer]}>
<Text style={styles.labelText}>{labelText || ''}</Text>
<View style={styles.inputWrapper}>
<TextInput style={styles.input} {...textInputProps} ref={ref} />
</View>
</View>
</>
);
},
);
Hope this gives you an idea.
not 100% sure what the question is here, but
<StyledInput
ref={ref}
testID="TextInputID"
placeholderTextColor={placeHolderColor}
placeholder={placeHolder}
...
should work, then you need to pass the ref in when calling this input.

Categories

Resources