I am doing something fundamentally wrong leveraging Redux and Material UI V1, and I am looking for help. I have not been able to successfully style the width of my Card component at 75 pixels.
How are we suppose to pass custom styles to our components leveraging withStyles and connect? I have been following an example here in Material UI's docs on the Paper component but have not been able to style my UI successfully. Below are code snippets of my presentational and container component:
Container:
import compose from 'recompose/compose';
import { connect } from 'react-redux';
import { withStyles } from 'material-ui/styles';
import Home from '../components/Home';
import * as homeActions from '../modules/home';
const styles = theme => ({
root: theme.mixins.gutters({
width: 75,
}),
});
const mapStateToProps = (state, ownProps = {}) => {
return {
props: {
classes: styles,
welcomeMessage: state.home.message || ''
}
};
};
const mapDispatchToProps = (dispatch, ownProps = {}) => {
dispatch(homeActions.loadPage());
return {
};
};
export default compose(
withStyles(styles),
connect(mapStateToProps, mapDispatchToProps)
)(Home)
Presentational:
import Card, { CardActions, CardContent, CardMedia } from 'material-ui/Card';
import Button from 'material-ui/Button';
import PropTypes from 'prop-types';
import React from 'react';
import ReactDOM from 'react-dom';
import Typography from 'material-ui/Typography';
import photo from './party.png';
const Component = ({props}) => {
return (
<div>
<Card classes={{
root: props.classes.card
}}>
This is Paper
</Card>
</div>
);
}
Component.propTypes = {
props: PropTypes.object.isRequired
};
export default Component;
EDIT:
I have also leveraged this SO post to see how the Redux and Material UI API for styling have been combined.
Also, I did not explicit state this but according to Material UI, all Paper props are valid for Card props in case you were wondering why I cited Paper documentation.
I also replaced code snippets where previously there were directly links to my project.
I think it is acceptable for your presentational component to express its own style.
Export your presentational component using withStyles:
import Card from 'material-ui/Card';
import { withStyles } from 'material-ui/styles';
import PropTypes from 'prop-types';
import React from 'react';
const styles = theme => ({
root: theme.mixins.gutters({
width: 75,
}),
});
const Component = ({ classes }) => {
return (
<div>
<Card className={classes.root}>This is Paper</Card>
</div>
);
};
Component.propTypes = {
classes: PropTypes.shape({
root: PropTypes.string,
}).isRequired,
};
export default withStyles(styles)(Component);
Then, in your container, you simply connect the presentational component's default export:
export default connect(mapStateToProps, mapDispatchToProps)(Home)
Related
Could you please help use to resolve this case
Parent component
const HelloMessage = (props) => {
return <>
<div className="main-counter" >
<top-destination name="srini" />
</div>
</>
}
export default HelloMessage
customElements.define("react-counter", reactToWebComponent(HelloMessage, React, ReactDOM));
Child (Web component)
import React from 'react';
import reactToWebComponent from "react-to-webcomponent";
const TopDestination = (props) => {
console.log(props);
return <>
<div>{props.name}</div>
</>
}
export default TopDestination
customElements.define("top-destination", reactToWebComponent(TopDestination, React, ReactDOM));
console log value
In html
<top-destination name="John" />
Cross-check your Node version, It should be Node 14 or above.
Cross-check your import ReactDom statement, based on the React version you are using.
Update to the latest version of react-to-webcomponent and prop-types
Your code should be like this:
Parent component
import React from 'react';
const HelloMessage = (props) => {
return <>
<div className="main-counter" >
<top-destination name="srini" />
</div>
</>
}
export default HelloMessage
customElements.define("react-counter", reactToWebComponent(HelloMessage, React, ReactDOM));
Child (Web component)
import React from 'react';
import PropTypes from "prop-types"
import * as ReactDOM from 'react-dom/client';
import reactToWebComponent from "react-to-webcomponent"
const TopDestination = (props) => {
console.log(props);
return <>
<div>{props.name}</div>
</>
}
TopDestination.propTypes = {
name: PropTypes.string,
}
customElements.define("top-destination", reactToWebComponent(TopDestination, React, ReactDOM));
export default TopDestination
// Other ways of defining the props if you are on better versions.
// customElements.define(
// "top-destination",
// reactToWebComponent(TopDestination, React, ReactDOM, {
// props: {
// name: String
// },
// }),
// )
// or
// customElements.define(
// "top-destination",
// reactToWebComponent(TopDestination, React, ReactDOM, {
// props: ["name"]
// }),
// )
Refer this repo: https://github.com/sarat9/cross-ui-web-comp
File: https://github.com/sarat9/cross-ui-web-comp/blob/master/react-web-components/src/web-components/FancyButtonWC.js
I wanted to get SVG icons dynamically. I found a method to do this but it seems I made some mistakes. Where am I doing it wrong?
Icon.js
import React from "react";
import { ReactComponent as Bollards } from "./icons/bollards.svg";
import { ReactComponent as Earthquake } from "./icons/earthquake.svg";
import { ReactComponent as Fire } from "./icons/fire.svg";
import { ReactComponent as Healthy } from "./icons/heartbeat.svg";
import { ReactComponent as Home } from "./icons/home.svg";
import { ReactComponent as Planting } from "./icons/planting.svg";
import { ReactComponent as Business } from "./icons/suitcase.svg";
import { ReactComponent as Travel } from "./icons/airplane-around-earth.svg";
const iconTypes = {
bollards: Bollards,
earthQuake: Earthquake,
fire: Fire,
healthy: Healthy,
home: Home,
planting: Planting,
business: Business,
travel: Travel
};
const IconComponent = ({ name, ...props }) => {
let Icon = iconTypes[name];
return <Icon {...props} />;
};
export default IconComponent;
Feautures.js
import React from "react";
import Icon from "./icon";
export default function Features() {
return (
<div>
<Icon name="bollards" />
</div>
);
}
I get this error when trying to export icons.
error - ./components/icon.js
Attempted import error: 'ReactComponent' is not exported from './icons/bollards.svg' (imported as 'Bollards').
You can use SVGR that allows us to import SVGs into your React applications as components.
You need to add #svgr/webpack as a dependency and modify the next.config.js file like this.
next.config.js:
module.exports = {
webpack(config) {
config.module.rules.push({
test: /\.svg$/,
use: ["#svgr/webpack"]
});
return config;
}
};
Then, you can simply import your icons without using ReactComponent.
Icon.js:
import React from "react";
import Bollards from './icons/bollards.svg';
import Earthquake from './icons/earthquake.svg';
import Fire from './icons/fire.svg';
import Healthy from './icons/heartbeat.svg';
import Home from './icons/home.svg';
import Planting from './icons/planting.svg';
import Business from './icons/suitcase.svg';
import Travel from './icons/airplane-around-earth.svg';
const iconTypes = {
bollards: Bollards,
earthQuake: Earthquake,
fire: Fire,
healthy: Healthy,
home: Home,
planting: Planting,
business: Business,
travel: Travel
};
const IconComponent = ({ name, ...props }) => {
let Icon = iconTypes[name];
return <Icon {...props} />;
};
export default IconComponent;
Working demo is available on CodeSandbox.
So react-admin seems to have a feature where if you're idle for a little while and come back it will reload the data, presumably to make sure you're looking at the most up to date version of a record.
This is causing some issues for my editing feature that has some custom components. Is there a way to disable this auto-reload feature?
The auto-refresh is triggered by the loading indicator (the spinner icon that you see in the top right part of the app bar).
You can disable the auto-refresh by replacing the loading indicator by your own.
import * as React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { useSelector } from 'react-redux';
import { makeStyles } from '#material-ui/core/styles';
import CircularProgress from '#material-ui/core/CircularProgress';
import { useRefreshWhenVisible, RefreshIconButton } from 'react-admin';
const useStyles = makeStyles(
{
loader: {
margin: 14,
},
loadedIcon: {},
},
{ name: 'RaLoadingIndicator' }
);
const LoadingIndicator = props => {
const { classes: classesOverride, className, ...rest } = props;
useRefreshWhenVisible(); // <= comment this line to disable auto-refresh
const loading = useSelector(state => state.admin.loading > 0);
const classes = useStyles(props);
return loading ? (
<CircularProgress
className={classNames('app-loader', classes.loader, className)}
color="inherit"
size={18}
thickness={5}
{...rest}
/>
) : (
<RefreshIconButton className={classes.loadedIcon} />
);
};
LoadingIndicator.propTypes = {
classes: PropTypes.object,
className: PropTypes.string,
width: PropTypes.string,
};
export default LoadingIndicator;
You'll also need to put this button in a custom AppBar, inject your AppBar in a custom Layout, and use that Layout in your Admin, as explained in the react-admin Theming documentation.
I was able to turn off auto-refresh by dispatching the setAutomaticRefresh action from react-admin:
import { setAutomaticRefresh } from 'react-admin';
import { useDispatch } from 'react-redux';
// inside component
const dispatch = useDispatch();
dispatch(setAutomaticRefresh(false))
This action was added here as part of release 3.8.2.
I have created a small application and connected it to Redux. Unfortunately when creating new components and using the same exact code those new components cannot seem to connect to redux and get undefined when accessing it (using mapStateToProps).
I have tried to create new Components and connect them again to no avail. I'm kind of at loss as to why it isn't working especially since the rest of the application can connect and get the state properly
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { Provider } from 'react-redux'
import store from './store'
ReactDOM.render(
<Provider store={store} >
<App />
</Provider>
, document.getElementById('root'));
store.js:
const initialState = {
guessedTimezone: '',
timezone: '',
pseudo: '',
};
function rootReducer(state = initialState, action) {
console.log(action);
if (action.type === 'CHANGE_TIMEZONE') {
return Object.assign({}, state, {
timezone: action.timezone,
guessedTimezone: action.guessedTimezone
})
}
if (action.type === 'CHANGE_PSEUDO') {
return Object.assign({}, state, {
pseudo: action.pseudo,
token: action.token
})
}
return state;
}
export default rootReducer;
new Component not connecting:
import React, { Component } from 'react'
import { connect } from 'react-redux'
export class TestPseudo extends Component {
render() {
console.log(this.props.pseudo);
return (
<div>
{this.props.pseudo}
</div>
)
}
}
const mapStateToProps = state => {
return {
pseudo: state.pseudo
}
}
export default connect(mapStateToProps)(TestPseudo)
Here for example this.props.pseudo returns undefined when, if the connection happens, it should return the value if i understand it correctly and yet it shows undefined
EDIT:
App.js as per requested :
import React, { Component } from 'react'
import { connect } from 'react-redux'
import Homepage from './Components/Homepage';
import moment from 'moment';
import moment_timezone from 'moment-timezone';
import HeaderApp from './Components/HeaderApp';
import { TestPseudo } from './Components/TestPseudo';
export class App extends Component {
async componentDidMount() {
let tz = moment.tz.guess(true);
let date = moment(new Date()).local();
let timezone = date['_i'].toString().split('(')[1].split(')')[0];
this.props.dispatch({
type: 'CHANGE_TIMEZONE',
guessedTimezone: tz,
timezone: timezone
})
console.log(`Guessed timezone: ${tz} (${timezone})`);
}
_showHomepage() {
if (this.props.showHomepage && this.props.loaded) {
return (
<div style={styles.mainWindow}>
{/*<Homepage click={this._handleClick} />*/}
<TestPseudo />
</div>
)
}
}
_showHeader() {
return (
<div>
<HeaderApp />
</div>
)
}
render() {
return (
<div>
{this._showHeader()}
{this._showHomepage()}
</div>
)
}
}
const styles = {
mainWindow: {
height: '100vh',
width: '100vw'
}
}
const mapStateToProps = state => {
return {
guessedTimezone: state.guessedTimezone,
timezone: state.timezone,
};
};
export default connect(mapStateToProps)(App);
I call that new Component instead of my old Component. The homepage can connect but not the new one so i think it's not a problem of emplacement
I think its here
import { TestPseudo } from './Components/TestPseudo';
You are importing the non-connected component. Try this
import TestPseudo from './Components/TestPseudo';
For your understanding, exporting as default can be imported like so;
export default Component
import WhateverName from ....
Named export like const or in your case class;
export class Component
import { Component } from ...
So use brackets when Named, and skip brackets when default.
I'm a bit confused about redux implementation.
Let's say my app has this component structure:
-App
--ProfilationStep
---ProfilationStep1
----React-Select (http://jedwatson.github.io/react-select/)
I need to use redux because the app is going to grow bigger and deeper, so I started by setting up Actions, Reducers and Action types for the React-Select component. I also set the mapStateToProps in the App.js file.
Now I need to know how to pass/access the data stored in redux to other components (React-Select for example) and how to edit it with the actions I declared.
This is my index.js file
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import ProfilationSelectReducer from './components/reducers/profilationSelect';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
const store = createStore(
ProfilationSelectReducer
);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>, document.getElementById('root'));
registerServiceWorker();
This is my App.js
import React, { Component } from 'react';
import PropTypes from 'prop-types'
import { bindActionCreators} from 'redux'
import Profilation from './components/Profilation'
import ProfilationStep from './components/Profilation/ProfilationStep'
import { connect } from 'react-redux';
import * as SelectActionCreators from './components/actions/profilationSelect'
import 'react-select/dist/react-select.css';
class App extends Component {
static propTypes = {
steps: PropTypes.array.isRequired
};
render() {
console.log(this.props)
const { dispatch, steps } = this.props;
const changeValue= bindActionCreators(SelectActionCreators.changeValue, dispatch);
const stepComponents = this.props.steps.map((step, index) => (
<ProfilationStep
key={index}
index={index}
step={step}
/>
));
return (
<div className="repower-app">
{ stepComponents }
</div>
);
}
}
const mapStateToProps = state => ({
steps:state.steps
});
export default connect(mapStateToProps)(App);
This is my ProfilationStep.js file
import React, { Component } from 'react';
import PropTypes from 'prop-types'
import ProfilationStep1 from './ProfilationStep1'
import ProfilationStep2 from './ProfilationStep2'
import ProfilationStep3 from './ProfilationStep3'
import ProfilationStep4 from './ProfilationStep4'
import ProfilationStep5 from './ProfilationStep5'
const ProfilationStep = props =>
<div className='ProfilationStep'>
{props.index===0 &&
<ProfilationStep1
step={props.step}
/>
}
{props.stepIndex===2 &&
<ProfilationStep2
handleSelect={props.handleSelect}
handleInput={props.handleInput}
expend={props.expend}
period={props.period}
light={props.light}
gas={props.gas}
/>
}
{props.stepIndex===3 &&
<ProfilationStep3
handleSelect={props.handleSelect}
environment={props.environment}
/>
}
{props.stepIndex===4 &&
<ProfilationStep4
flexibility={props.flexibility}
handleSelect={props.handleSelect}
/>
}
{props.stepIndex===5 &&
<ProfilationStep5
customize={props.customize}
handleSelect={props.handleSelect}
/>
}
</div>
export default ProfilationStep
This is my ProfilationStep1.js file
import React, { Component } from 'react';
import Select from 'react-select';
import PropTypes from 'prop-types'
var jobOptions = [
{ value: 'edilizia', label: 'Edilizia' },
{ value: 'editoria', label: 'Editoria' },
{ value: 'educazione', label: 'Educazione' }
];
const ProfilationStep1 = props =>
<div className='ProfilationStep'>
La mia attività si occupa di <Select
name="job"
value={props.step.job}
onChange={e => props.changeValue(e.target.value)}
options={jobOptions}
/>
</div>
ProfilationStep1.propTypes = {
//isComplete: PropTypes.bool.isRequired,
//isActive: PropTypes.bool.isRequired
job: PropTypes.string.isRequired,
service: PropTypes.string.isRequired,
handleSelect: PropTypes.func.isRequired
}
export default ProfilationStep1
This is my reducer
import * as ProfilationSelectActionTypes from '../actiontypes/profilationSelect';
const initialState = {
steps: [{
job: "",
service: ""
}],
}
export default function ProfilationSelectReducer (state=initialState, action){
switch(action.type){
case ProfilationSelectActionTypes.CHANGE_VALUE:
return {
...state,
steps:[{
job: action.value
}]
};
default:
return state;
}
}
This is my actiontypes file
export const CHANGE_VALUE ='profilationSelect/CHANGE_VALUE';
and, finally, this is my actions file
import * as ProfilationSelectActionTypes from '../actiontypes/profilationSelect';
export const changeValue = value =>{
return{
type: ProfilationSelectActionTypes.CHANGE_VALUE,
value
}
}
Thank you for any help
You are definitely on the right way.
The solution is simple: You bind your state to the react props. With the props, you can do whatever you like (e.g. pass them to react-select). If you want to modify it, you have to map "mapDispatchToProps", where you map functions, which execute your actions to the props. This works the same as "mapStateTopProps":
End of App.js (import your actions file on top, named "profilationSelectActions" here):
const mapStateToProps = state => ({
steps:state.steps
});
const mapDispatchToProps = dispatch => ({
updateJobValue: (value) => dispatch(profilationSelectActions.changeValue(value))
}
// Also add here mapDispatchToProps
export default connect(mapStateToProps, mapDispatchToProps)(App);
Now the function "updateJobValue" is available in the props of your app.js. You can now easily pass it down to your components and to the onChange event of react-select:
In your ProfilationStep1.js change this line:
onChange={e => props.changeValue(e.target.value)}
To this (after you passed the function updateJobValue down)
onChange{e => props.updateJobType(e.target.value)}
After that, updateJobType should go all the way up to App.js and then dispatch the action. After that, the application will re-render with the new steps.