Search code examples
reactjsreact-admin

In react-admin, how can I prefix a UrlField href?


Let's say I have the following:

<UrlField source='fbUsername' />

If the result is fb username foo, this links relatively to /foo.

(?) How can I prefix this url to:

https://facebook.com/

So the result would be:

https://facebook.com/${fbUsername}

https://facebook.com/foo


Solution

  • Based on @françois-zaninotto 's answer, I fixed a syntax error fixed some of the missing useRecordContext() param that made it work:

    // ###############################################
    // FbUrlField.js
    import * as React from 'react';
    import { Link } from '@material-ui/core';
    import { useRecordContext } from 'react-admin';
    
    const FbUrlField = ( props ) =>
    {
        const { source, target, rel } = props;
        const record = useRecordContext(props);
        const value = record && record[source];
    
        if (value == null) {
            return null;
        }
    
        return (
            <Link href={`https://facebook.com/${value}`} target={target} rel={rel}>
                {value}
            </Link>
        );
    };
    
    FbUrlField.defaultProps = {
        addLabel: true,
    };
    
    export default FbUrlField;
    
    
    // ###############################################
    // SomeList.js
    import FbUrlField from './FbUrlField';
    [...]
    <FbUrlField
        label='FB'
        source='fbUsername'
        target='_blank' // New window
        rel="noopener noreferrer" // For security
    />