Search code examples
admin-on-restreact-admin

TypeError: translate is not a function


There is no errors and warnings in compiling but when i launch my project i get this error :

TypeError: translate is not a function
  289 | inputProps={{
> 291 |     placeholder: translate('labels.search') + '...',

I'm using react-admin 2.3.3, i can post my packages.json if you want. I tried to clean my modules and install it again without success.

This is my compoment (simplified code) :

import React from 'react'
import PropTypes from 'prop-types'
import deburr from 'lodash/deburr'
import Autosuggest from 'react-autosuggest'
import match from 'autosuggest-highlight/match'
import parse from 'autosuggest-highlight/parse'
import TextField from '@material-ui/core/TextField'
import Paper from '@material-ui/core/Paper'
import MenuItem from '@material-ui/core/MenuItem'
import Popper from '@material-ui/core/Popper'
import ListItem from '@material-ui/core/ListItem'
import ListItemIcon from '@material-ui/core/ListItemIcon'
import ListItemText from '@material-ui/core/ListItemText'
import Avatar from '@material-ui/core/Avatar'
import Divider from '@material-ui/core/Divider'
import SearchIcon from '@material-ui/icons/Search'
import { withStyles } from '@material-ui/core/styles'
import { fade } from '@material-ui/core/styles/colorManipulator'
import { Link } from 'react-router-dom'

const styles = theme => ({})

class TestComponent extends React.Component {
    render() {
        const { classes } = this.props
        const { translate } = this.context

        return (
            <div className={classes.root}>
                <Autosuggest
                    inputProps={{
                        placeholder: translate('labels.search') + '...',
                    }}
                />
            </div>
        )
    }
}

TestComponent.propTypes = {
    classes: PropTypes.object.isRequired,
}

TestComponent.contextTypes = {
    translate: PropTypes.func,
}

export default withStyles(styles)(TestComponent)

Solution

  • You must import the translate HOC from react-admin and apply it to your component:

    import { translate } from 'react-admin`;
    
    export default translate(withStyles(styles)(TestComponent));
    

    Then, you should get the translate function injected by this HOC from your props instead of context:

    const { classes, translate } = this.props