TypeError: translate is not a function - admin-on-rest

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)

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

Related

D3 Graphviz d3.select.graphviz is not a function

I am trying to run this below ReactJs code and I am getting an error:
d3.select.graphviz() is not a function
import * as React from "react"
import * as ReactDOM from "react-dom"
import * as d3 from 'd3'
import * as d3Graphviz from 'd3-graphviz'
const _ = d3Graphviz.graphviz ;
class DotViewer extends React.Component<{},{}>{
constructor(props){
super(props)
this.renderGraph = this.renderGraph.bind(this)
}
render(){
return <div className='DotViewer'>
<div className='dot_view_port'></div>
</div>
}
componentDidMount(){this.renderGraph()}
renderGraph(){
d3.select(".dot_view_port").graphviz().renderDot("digraph{a->b}")
}
}
ReactDOM.render(<DotViewer/>, document.getElementById("main"))
I read about an article which said adding const _ = d3Graphviz.graphviz ; would be the fix. But it didn't solve the issue.
However d3Graphviz.graphviz worked for me.
I would like to know what could be the fix for using
d3.select(".dot_view_port").graphviz().renderDot("digraph{a->b}") without an error.
For d3-graphviz#2.6.1, you can use graphviz(`xxx`).renderDot(`digraph{a->b}`). Example:
import React, { Component } from "react";
import {graphviz} from "d3-graphviz";
class Dot extends Component{
constructor(props) {
super();
this.draw = this.draw.bind(this);
}
componentDidMount() {
this.draw()
}
draw(){
graphviz(`#graph-body`).renderDot(`digraph{a->b}`);
}
render(){
return(
<div id="graph-body">
</div>
)
}
}
export default Dot;

Passing props from component to TabNavigator - React-Navigation

I'm currently working on a React Native project for Android. Now I created a TabNavigator using React Navigations createMaterialTopTabNavigator, which displays two tabs:
It would be nice to use this TabNavigator as a reusable component. Therefore, I'm trying to pass props from the component that is calling the navigator. Unfortunately, I can't figure out how to pass the props correctly.
This is the component that calls the TabNavigator (named TwoTabsHorizontal here):
import React from 'react';
import {View, StyleSheet} from 'react-native';
import {withNavigation} from 'react-navigation';
import Background from '../../atoms/Background/Background';
import TwoTabsHorizontal from '../../molecules/TwoTabsHorizontal/TwoTabsHorizontal';
class Main extends React.Component {
render() {
return (
<View style={styles.view}>
<Background background={true} title="Find Dogs" />
<TwoTabsHorizontal
headingLeftTab="criteria"
headingRightTab="names"
/>
</View>
);
}
}
const styles = StyleSheet.create({
view: {
backgroundColor: '#151414',
height: '100%',
},
});
export default withNavigation(Main);
And this is the TabNavigator TwoTabsHorizontal:
import React from 'react';
import {View, StyleSheet} from 'react-native';
import {createMaterialTopTabNavigator} from 'react-navigation-tabs';
import {createAppContainer} from 'react-navigation';
import TestScreen1 from '../../../screens/TestScreen1';
import TestScreen2 from '../../../screens/TestScreen2';
const TabNavigator = ({headingLeftTab}) =>
createMaterialTopTabNavigator(
{
One: {
screen: TestScreen1,
navigationOptions: {
tabBarLabel: {headingLeftTab},
},
},
Two: {
screen: TestScreen2,
navigationOptions: {
tabBarLabel: 'Names',
},
},
},
{
},
);
export const TwoTabsHorizontal = createAppContainer(TabNavigator);
As you can see, I try to pass the prop headingLeftTab from Main down to TwoTabsHorizontal to use it as label in navigationOptions. It gives the following error:
I already tried the approach that is suggested here.

Redux state changed but component props is not updating

I am using redux to control an Ant Design Modal component with a boolean state. Basically it has a button that dispatch action to change the state, and the component will read the state value.
The state is changed properly but the component props value is not updating accordingly. Not sure why it is not working.
I have tried different approaches in reducer like creating a new boolean object to avoid mutating the state but no luck.
myAction.js
export const modalVisibilityOn = () => ({
type: 'MODAL_ON'
})
export const modalVisibilityOff = () => ({
type: 'MODAL_OFF'
})
myReducer.js
const modalVisibility = (state = false, action) => {
switch (action.type){
case 'MODAL_ON':
return true
case 'MODAL_OFF':
return false
default:
return state
}
}
export default modalVisibility
myRootReducer.js
import { combineReducers } from 'redux'
import modalVisibility from './signPage/myReducer'
export default combineReducers({
modalVisibility
})
myModal.js
import React from "react";
import PropTypes from 'prop-types'
import { Modal, Input } from 'antd';
import { connect } from 'react-redux'
import { modalVisibilityOff } from '../../reducers/signPage/myAction'
class myModal extends React.Component {
render() {
const { visibility, handleOk, handleCancel } = this.props;
myModal.propTypes = {
visibility: PropTypes.bool.isRequired,
handleOk: PropTypes.func.isRequired,
handleCancel: PropTypes.func.isRequired,
}
return (
<Modal
title="Sign"
visible={visibility}
onOk={handleOk}
onCancel={handleCancel}
closable={false}
>
<p>Please input your staff ID</p>
<Input addonBefore="Staff ID" />
</Modal>
);
}
}
const mapStateToProps = state => {
return {
visibility: state.modalVisibility
}
}
const mapDispatchToProps = dispatch => ({
handleOk: () => dispatch(modalVisibilityOff()),
handleCancel: () => dispatch(modalVisibilityOff()),
})
export default connect(
mapStateToProps,mapDispatchToProps
)(myModal)
myModalContainer.js
import React from "react";
import { Input } from "antd";
import { Button } from 'antd';
import { Row, Col } from 'antd';
import { Typography } from 'antd';
import PropTypes from 'prop-types'
import myModal from '../../dialogs/signPage/myModal';
import { connect } from 'react-redux'
import { modalVisibilityOn } from '../../reducers/signPage/myAction'
class myModalContainer extends React.Component {
render() {
const { Title } = Typography;
const { onClick } = this.props;
myModalContainer.propTypes = {
onClick: PropTypes.func.isRequired
}
return (
<div className="search-container-parent">
<Row className="search-container">
<Col className="search-col1" xs={24} sm={12}>
<Input size="large" style={{width:'40%'}} id="issueReturnNo" placeholder="QR code here"/>
<Button size="large">SEARCH</Button>
<div className="signBtn-div">
<Button size="large" type="primary" onClick={onClick} >SIGN</Button>
<myModal />
</div>
</Col>
<Col xs={24} sm={12}>
<Title className="issueLog-title" level={3} style={{color:"#F08080"}}>Issue</Title>
</Col>
</Row>
</div>
);
}
}
const mapDispatchToProps = dispatch => ({
onClick: () => dispatch(modalVisibilityOn())
})
export default connect(
null, mapDispatchToProps
)(myModalContainer);
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import rootReducer from './myRootReducer'
const store = createStore(rootReducer,window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__())
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root'));
serviceWorker.unregister();
I expect the visibility props on myModal.js would be true when the sign button on myModalContainer.js is clicked, but the it keep showing false.
Any help would be appreciated. Thanks!
After lots of researches and trials, It turns out that my code has no problem..
The reason why it is not working as expected, is due to the redux and react-redux version. After switching package.json dependencies versions back to the one that redux official tutorial are using, the application is running without any problem.
In case anyone have the same problem, here is the version I am using now for my app in npm:
redux: ^3.5.2
react-redux: ^5.0.7
Update:
Just found out that the cause of the problem comes from conflicts between older version modules and newer version modules.
Therefore by updating all the dependencies in package.json to the latest version, the app can also run smoothly. It is not necessary to downgrade react-redux and redux.

typeerror _this.store is not defined react redux

I am currently following this tutorial (https://medium.com/#viewflow/full-stack-django-quick-start-with-jwt-auth-and-react-redux-part-ii-be9cf6942957) which is essentially a guide on implementing JWT authentication with Django REST Framework and React.
However, upon compiling the code given on the repository posted by the author(s), I've been getting a specific error:
"TypeError: _this.store is undefined"
and after trawling through the web, I've not been able to find an answer to the problem I face.
Would appreciate any help I can get, thank you!
This tutorial uses react-router-redux which is deprecated. What you could do is use connected-react-router instead. So your src/index.js would look like
import React from 'react';
import ReactDOM from 'react-dom';
import { ConnectedRouter } from 'connected-react-router';
import { Provider } from 'react-redux';
import App from './App';
import configureStore, { history } from './store';
const store = configureStore();
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<App />
</ConnectedRouter>
</Provider>,
document.getElementById('root')
Your store would now take a preloadedState variable like
import storage from 'redux-persist/es/storage';
import { createBrowserHistory } from 'history';
import { apiMiddleware } from 'redux-api-middleware';
import { applyMiddleware, compose, createStore } from 'redux';
import { createFilter } from 'redux-persist-transform-filter';
import { persistReducer, persistStore } from 'redux-persist';
import { routerMiddleware } from 'connected-react-router';
import rootReducer from './reducers';
export const history = createBrowserHistory();
export default function configureStore(preloadedState) {
const persistedFilter = createFilter('auth', ['access', 'refresh']);
const reducer = persistReducer(
{
key: 'polls',
storage: storage,
whitelist: ['auth'],
transforms: [persistedFilter],
},
rootReducer(history)
);
const store = createStore(
reducer,
preloadedState,
compose(applyMiddleware(apiMiddleware, routerMiddleware(history)))
);
persistStore(store);
return store;
}
Now your root reducer will take history as an argument:
import { combineReducers } from 'redux';
import { connectRouter } from 'connected-react-router';
import auth, * as fromAuth from './auth.js';
export default history =>
combineReducers({
router: connectRouter(history),
});
export const isAuthenticated = state => fromAuth.isAuthenticated(state.auth);
...

Using redux-connected component as screen in StackNavigator

I'm creating an react native app using create-react-native-app, react-navigation and react-redux. I'm trying to add a redux-connected component as a screen into a nested StackNavigator (though the nesting seems to not make a difference, it doesn't work either way) and consistently am getting an error message saying Route 'MilkStash' should declare a screen. When I remove the redux connection from the MilkStash.js file, everything works fine. Any idea how to get this working?
App.js
import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import rootReducer from './src/reducers';
import AppWithNavigation from './src/AppWithNavigation';
export default () => (
<Provider store = {createStore(rootReducer)}>
<AppWithNavigation />
</Provider>
);
AppWithNavigation.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { StyleSheet, Text, View, Image, Button } from 'react-native';
import { DrawerNavigator, StackNavigator } from 'react-navigation';
import MilkStash from './screens'
import { StatsScreen, FAQScreen, AddMilk, AccountScreen } from './screens';
export default class AppWithNavigation extends React.Component {
render() {
return (
<MenuNavigator />
);
}
}
const MilkNavigator = StackNavigator(
{ Milk: { screen: MilkStash},
AddMilk: { screen: AddMilk }
},
);
const AccountNavigator = StackNavigator(
{ Account: {screen: AccountScreen}}
);
const StatsNavigator = StackNavigator(
{ Stats: {screen: StatsScreen }}
);
const FAQNavigator = StackNavigator(
{ FAQ: {screen: FAQScreen}}
)
const MenuNavigator = DrawerNavigator({
Milk: { screen: MilkNavigator},
Account: {screen: AccountNavigator},
Stats: {screen: StatsNavigator},
FAQ: {screen: FAQNavigator},
}
);
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#ecf0f1',
}
});
MilkStash.js
import React, {Component} from 'react';
import { StyleSheet, Text, View} from 'react-native';
import { StackNavigator } from 'react-navigation';
import { connect } from 'react-redux';
import { Milk } from '../../core/models/milk';
import styles from './styles.js';
export class MilkStash extends Component {
constructor(props){
super(props);
}
render() {
return (
<View style={styles.container}>
....displaying data goes here
</View>
)
}
}
function mapStateToProps(state){
return{
milkStash: state.milkStash
}
}
function mapDispatchToProps(dispatch){
return {
addMilk: (milk) => dispatch(addMilk(milk)),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(MilkStash);
milk-reducer.js
import {ADD_MILK} from '../constants';
const milkReducer = (state = {milkStash: []}, action = {}) => {
switch(action.type){
case ADD_MILK:
var item = action.payload;
return state
.update('milkStash', (milkStash) =>
{
var milkStashCopy = JSON.parse(JSON.stringify(milkStash));
milkStashCopy.concat(item);
return milkStashCopy;
});
default:
return state;
}
}
export default milkReducer;
reducers.js
export * from './milk.js';
import milkReducer from './milk';
import { combineReducers } from 'redux';
export default rootReducer = combineReducers({
milk: milkReducer
});
I figured out the answer and thought I would help prevent someone else struggling with this for 3 days. The issue had to do with the way I was importing the exports from MilkStash.js. Apparently using import MilkStash from './screens' will cause the error but changing it to import MilkStashContainer from './screens/MilkStash/MilkStash.js will fix the problem.

Resources