import { useContext } from 'react'; import { RaRecord } from '../../types'; import { RecordContext } from './RecordContext'; /** * Hook to read the record from a RecordContext. * * Must be used within a such as provided by the * (e.g. as a descendent of or ) or within a * (e.g. as a descendent of or ) * * @example // basic usage * * import { useRecordContext } from 'ra-core'; * * const TitleField = () => { * const record = useRecordContext(); * return {record && record.title}; * }; * * @example // allow record override via props * * import { useRecordContext } from 'ra-core'; * * const TitleField = (props) => { * const record = useRecordContext(props); * return {record && record.title}; * }; * render(); * * @returns {RaRecord} A record object */ export const useRecordContext = < RecordType extends RaRecord | Omit = RaRecord >( props?: UseRecordContextParams ): RecordType | undefined => { // Can't find a way to specify the RecordType when CreateContext is declared // @ts-ignore const context = useContext(RecordContext); return (props && props.record) || context; }; export interface UseRecordContextParams< RecordType extends RaRecord | Omit = RaRecord > { record?: RecordType; [key: string]: any; }