Passing custom props to component with redux-form 7 - javascript

I am using the following libraries
"#material-ui/core": "^3.0.3",
"react": "^16.5.0",
"redux": "^4.0.0",
"redux-form": "^7.4.2",
How do I pass custom props to my component property of the redux-form <Field />?
According to this example from redux-form everything I have below should work, but it is not pulling the multiline={true} or rows={2} props into the <TextField /> component.
I am not sure how it is supposed to work as I am a novice with javascript. Any help would be appreciated.
PostForm.js
import React from 'react'
import { Link, withRouter } from 'react-router-dom';
import { reduxForm, Field } from 'redux-form';
import Button from '#material-ui/core/Button';
import TextField from '#material-ui/core/TextField'
class PostForm extends React.Component {
renderTextField = ({ input,
label,
meta: { error, touched } },
...custom) => {
return (
<TextField
name={label}
label={label}
{...input}
{...custom}
/>
);
};
onSubmit(event) {
event.preventDefault();
const { submitPost, history, formValues } = this.props;
submitPost(formValues.values, history);
}
render() {
<form onSubmit={this.onSubmit.bind(this)}>
<Field
name="title"
component={this.renderTextField}
label="Title"
/>
<Field
name="body"
component={this.renderTextField}
label="Body"
multiline={true}
rows={2}
/>
<div className={classes.buttonContainer}>
<Button to="/posts" component={Link} className={classes.button} color='secondary'>
Cancel
</Button>
<Button type='submit' className={classes.button} color='primary'>
Next
</Button>
</div>
</form>
}
}
export default reduxForm({
validate,
form: 'postForm',
destroyOnUnmount: false
})(PostForm)

To render multi line fields, you need to pass multiLine={true} (notice the camel casing - this is important). This is based on docs linked from https://github.com/erikras/redux-form-material-ui which seem like old version. According to newer docs, it seems multiline is all lowercase (leaving it here for posterity's sake).
Update
Also, ...custom is outside of the curly braces. Should be
renderTextField = ({ input, label, meta: { error, touched } , ...custom })
A bit about how Field passes props down - it's not enough to cover everything in this answer but I can give a few pointers to help you get started.
<Field ... /> is JSX notation. While JSX makes it easy to read and wirte HTML constructs, [React actually doesn't need JSX][1]. Internally, they all compile to pure JS functions (using React.createElement and other factory functions).
After that, passing ...custom etc. is just rest/spread operators introduced in ES6. They are shortcuts, and you can use React without them as well (meaning you can use just ES5 syntax).

Related

How to link to next page url in handleSubmit formik?

I have two functional components in my process. First, I need the first component info to be filled and validated by Formik and Yup and then user can process the next step in the second component by click Next. For now, I can get everything validated and code can reach on handleSubmit() without any problem. But, the problem is that, I could not link to another component using <Link>. I have tried:
// Using this first one, no validation is performed and it will link to another component directly
<Link to="/Next">
<button type="submit">Next</Button>
</Link>
// I have put these inside handleSubmit() but it is undefined.
this.context.router.push('/Next');
Router.push('/Next')
this.props.history.push('/Next')
Mostly I got undefined output on console using these code. It's seems like that i could not access props from functional components like i could in the react class. Here is my first component:
import React from 'react';
import { withFormik, Field } from 'formik';
import {
BrowserRouter as Router,
Route,
Link,
Switch,
Redirect
} from "react-router-dom";
const MyForm = props => { const {handleSubmit} = props;
return (
<form onSubmit={handleSubmit}>
<Field type="email" name="email" placeholder="Email" />
<button type="submit">Next</button>
// <Link to="/Next">
// <button type="submit">Next</Button>
// </Link>
</Field>
);
};
const MyEnhancedForm = withFormik({
mapPropsToValues: () => ({ email: '' }),
handleSubmit: (values, formikBag) => {
// Link to next page code
},
})(MyForm);
Yes we can't use this.props in functional components but what we can do is that write the same routing logic in parent component and pass it as a prop in the functional component.
Then we can call the same function in handleSubmit().
If you are using hooks you can follow the approach described in this blog post https://dev.to/httpjunkie/programmatically-redirect-in-react-with-react-router-and-hooks-3hej in order to programmatically redirect with react-router and hooks. A summary:
Include useState in your imports:
import React, { useState } from 'react';
Inside your functional component add:
const [toNext, setToNext] = useState(false)
Inside handleSubmit add:
setToNext(true)
Inside the <form> add:
{toNext ? <Redirect to="/Next" /> : null}

Calling parent component method from child component written in Jsx Vue

I didn't expect it be tough.
I've a child component written like
InputWrapper.vue
<script>
import StyledInput from "./input";
export default {
name: "MyInput",
props: {
multiline: Boolean,
onChange: Function
},
render(h) {
const { multiline, onChange } = this;
console.log(onChange);
return (
<div>
<StyledInput multiline={multiline} onChange={e => onChange(e)} />
</div>
);
}
};
</script>
Then I have actual input as vue-styled-components as Input.js. For those familiar with styled components need not explain that code.
Then I consume this InputWrapper component in my parent component Home.vue
<template>
<div class="pLR15 home">
<Row>
<MyInput :multiline="true" placeholder="Sample Input" type="text" :onChange="handleChange"></MyInput>
</Row>
</div>
</template>
<script>
// # is an alias to /src
import HelloWorld from "#/components/HelloWorld.vue";
import Row from "#/ui_components/row";
import MyInput from "#/ui_components/form/input/index.vue";
export default {
name: "home",
components: {
HelloWorld,
Row,
MyInput
},
methods: {
handleChange: function(e) {
console.log("Hey you are changing my value to", e.target.value);
}
}
};
</script>
Problem - onChange on parent is not fired.
#change.native="handleChange" did the trick for me. Also I cleaned up all the event handlers listening on child. Since my type and placeholder properties were passing down as such, so should be the event listeners. With that thought the .native modifier works best for now. Although things could have been uniform by just #change="handleChange" which I was trying earlier and lead to trying out passing function as props to child.
IMP NOTE - Vuejs doesn't treats #change as normal onChange. #input is preferred if the idea is to capture every keystroke. Here comes the opinions! :)

infinite Render in React

I am having problem figuring out why my application is doing endless render.
Inside, My stateful component, I am calling a redux action in componentDidMount method (calling componentWillMount also do endless render)
class cryptoTicker extends PureComponent {
componentDidMount() {
this.props.fetchCoin()
// This fetches some 1600 crypto coins data,Redux action link for the same in end
}
render() {
return (
<ScrollView>
<Header />
<View>
<FlatList
data={this.state.searchCoin ? this.displaySearchCrypto : this.props.cryptoLoaded}
style={{ flex: 1 }}
extraData={[this.displaySearchCrypto, this.props.cryptoLoaded]}
keyExtractor={item => item.short}
initialNumToRender={50}
windowSize={21}
removeClippedSubviews={true}
renderItem={({ item, index }) => (
<CoinCard
key={item["short"]}
/>
)}
/>
</View>
</ScrollView>
)
}
}
In CoinCard I am literally doing nothing besides this (Notice CoinCard inside Flat list)
class CoinCard extends Component {
render () {
console.log("Inside rende here")
return (
<View> <Text> Text </Text> </View>
)
}
}
Now, When I console log in my coincard render, I can see infinite log of Inside rende here
[Question:] Can anyone please help me figure out why this could be happening?
You can click here to see my actions and click here to see my reducer.
[Update:] My repository is here if you want to clone and see it by yourself.
[Update: 2]: I have pushed the above shared code on github and it will still log endless console.log statements (if you can clone, run and move back to this commit ).
[Update:3]: I am no longer using <ScrollView /> in <FlatList /> also when I mean endless render, I mean is that it is endless (& Unecessarily) passing same props to child component (<Coincard />), if I use PureComponent, it won't log endlessly in render () { but in componentWillRecieveProps, If I do console.log(nextProps), I can see the same log passed over and over again
There are some points to note in your code.
The CoinCard Component must be a PureComponent, which will not re-render if the props are shallow-equal.
You should not render your Flatlist inside the ScrollView component, which would make the component render all components inside it at once which may cause more looping between the Flatlist and ScrollView.
You can also a definite height to the rendered component to reduce the number of times component is rendered for other props.
Another thing to note is, only props in the component are rendered on scroll bottom, based on the log statement mentioned below.
import {Dimensions} from 'react-native'
const {width, height} = Dimensions.get('window)
class CoinCard extends React.PureComponent {
render () {
console.log(this.props.item.long) //... Check the prop changes here, pass the item prop in parent Flatlist. This logs component prop changes which will show that same items are not being re-rendered but new items are being called.
return (
<View style={{height / 10, width}}> //... Render 10 items on the screen
<Text>
Text
</Text>
</View>
)
}
}
UPDATE
This extra logging is due to the props being from the Flatlist to your component without PureComponent shallow comparison.
Note that componentWillReceiveProps() is deprecated and you should avoid them in your code.
React.PureComponent works under the hood and uses shouldComponentUpdate to use shallow comparison between the current and updated props. Therefore log console.log(this.props.item.long) in your PureComponent' render will log the unique list which can be checked.
Like izb mentions, the root cause of the pb is the business call that is done on a pure component whereas it is just loaded. It is because your component make a business decision (<=>"I decide when something must be showed in myself"). It is not a good practice in React, even less when you use redux. The component must be as stupid a possible and not even decide what to do and when to do it.
As I see in your project, you don't deal correctly with component and container concept. You should not have any logic in your container, as it should simply be a wrapper of a stupid pure component. Like this:
import { connect, Dispatch } from "react-redux";
import { push, RouterAction, RouterState } from "react-router-redux";
import ApplicationBarComponent from "../components/ApplicationBar";
export function mapStateToProps({ routing }: { routing: RouterState }) {
return routing;
}
export function mapDispatchToProps(dispatch: Dispatch<RouterAction>) {
return {
navigate: (payload: string) => dispatch(push(payload)),
};
}
const tmp = connect(mapStateToProps, mapDispatchToProps);
export default tmp(ApplicationBarComponent);
and the matching component:
import AppBar from '#material-ui/core/AppBar';
import IconButton from '#material-ui/core/IconButton';
import Menu from '#material-ui/core/Menu';
import MenuItem from '#material-ui/core/MenuItem';
import { StyleRules, Theme, withStyles, WithStyles } from '#material-ui/core/styles';
import Tab from '#material-ui/core/Tab';
import Tabs from '#material-ui/core/Tabs';
import Toolbar from '#material-ui/core/Toolbar';
import Typography from '#material-ui/core/Typography';
import AccountCircle from '#material-ui/icons/AccountCircle';
import MenuIcon from '#material-ui/icons/Menu';
import autobind from "autobind-decorator";
import * as React from "react";
import { push, RouterState } from "react-router-redux";
const styles = (theme: Theme): StyleRules => ({
flex: {
flex: 1
},
menuButton: {
marginLeft: -12,
marginRight: 20,
},
root: {
backgroundColor: theme.palette.background.paper,
flexGrow: 1
},
});
export interface IProps extends RouterState, WithStyles {
navigate: typeof push;
}
#autobind
class ApplicationBar extends React.PureComponent<IProps, { anchorEl: HTMLInputElement | undefined }> {
constructor(props: any) {
super(props);
this.state = { anchorEl: undefined };
}
public render() {
const auth = true;
const { classes } = this.props;
const menuOpened = !!this.state.anchorEl;
return (
<div className={classes.root}>
<AppBar position="fixed" color="primary">
<Toolbar>
<IconButton className={classes.menuButton} color="inherit" aria-label="Menu">
<MenuIcon />
</IconButton>
<Typography variant="title" color="inherit" className={classes.flex}>
Title
</Typography>
<Tabs value={this.getPathName()} onChange={this.handleNavigate} >
{/* <Tabs value="/"> */}
<Tab label="Counter 1" value="/counter1" />
<Tab label="Counter 2" value="/counter2" />
<Tab label="Register" value="/register" />
<Tab label="Forecast" value="/forecast" />
</Tabs>
{auth && (
<div>
<IconButton
aria-owns={menuOpened ? 'menu-appbar' : undefined}
aria-haspopup="true"
onClick={this.handleMenu}
color="inherit"
>
<AccountCircle />
</IconButton>
<Menu
id="menu-appbar"
anchorEl={this.state.anchorEl}
anchorOrigin={{
horizontal: 'right',
vertical: 'top',
}}
transformOrigin={{
horizontal: 'right',
vertical: 'top',
}}
open={menuOpened}
onClose={this.handleClose}
>
<MenuItem onClick={this.handleClose}>Profile</MenuItem>
<MenuItem onClick={this.handleClose}>My account</MenuItem>
</Menu>
</div>
)}
</Toolbar>
</AppBar>
</div >
);
}
private getPathName(): string {
if (!this.props.location) {
return "/counter1";
}
return (this.props.location as { pathname: string }).pathname;
}
private handleNavigate(event: React.ChangeEvent<{}>, value: any) {
this.props.navigate(value as string);
}
private handleMenu(event: React.MouseEvent<HTMLInputElement>) {
this.setState({ anchorEl: event.currentTarget });
}
private handleClose() {
this.setState({ anchorEl: undefined });
}
}
export default withStyles(styles)(ApplicationBar);
Then you will tell me: "but where do I initiate the call that will fill my list?"
Well I see here that you use redux-thunk (I prefer redux observable... more complicated to learn but waaaaaaaaaaaaaaaaay more powerful), then this should be thunk that initiates the dispatch of this!
To summarize:
Components: the stupidest element that normally should have only the render method, and some other method handler to bubble up user events. This method only takes care of showing its properties to the user. Don't use the state unless you have a visual information that belongs only to this component (like the visibility of a popup for example). Anything that is showed or updated comes from above: a higher level component, or a container. It doesn't decide to update its own values. At best, it handles a user event on a subcomponent, then bubble up another event above, and... well maybe at some point, some new properties will be given back by its container!
Container: very stupid logic that consists in wrapping a top level component into redux for it to plug events to actions, and to plug some part of the store to properties
Redux thunk (or redux observable): it is the one that handles the whole user application logic. This guy is the only one who knows what to trigger and when. If a part of your front end must contain the complexity, it's this one!
Reducers: define how to organize the data in the store for it to be as easily usable as possible.
The store: ideally one per top level container, the only one that contains the data that must be showed to the user. Nobody else should.
If you follow these principles, you should never face any issue like "why the hell this is called twice? and... who made it? and why at this moment?"
Something else: if you use redux, use an immutability framework. Otherwise you may face issues as reducers must be pure functions. For this you can use a popular one immutable.js but not convenient at all. And the late ousider that is actually a killer: immer (made by the author or mobx).
It seems Jacob in the above comment has managed to make the component render only twice.
This will definitely cause double initial render (and would cause an infinite render if it wasn't a PureComponent):
componentDidUpdate() {
var updateCoinData;
if (!updateCoinData) { // <- this is always true
updateCoinData = [...this.props.cryptoLoaded];
this.setState({updateCoinData: true}); // <- this will trigger a re render since `this.state.updateCoinData` is not initially true
}
...
}
Link to the issue in your repository

React Form with file submission

I am now practicing upload a file by using Reactjs. This is a simple problem, but I could not connect the solution to axios. I know how the state and Form works, but my JavaScript callback values does not contains any of my given input. Or I could not find my values. Here is my case.
import React, {Component, Fragment} from 'react';
import tokamakConfig from './Configuration_icon_by_obsilion.png';
import {Form} from 'semantic-ui-react';
class Advance extends Component {
handleSubmit(event, values){
console.log(event);
console.log(values);
}
render() {
return (
<Fragment>
<h1>Please provide necessary information for the operation</h1>
<img src={tokamakConfig} alt={'tokamak configuration'} />
<Form onSubmit={this.handleSubmit}>
<Form.Group inline>
<label>Load input file</label>
<input name={'file'} type='file' />
</Form.Group>
<Form.Group inline>
<label>Comment</label>
<input name={'comment'} type={'text'} placeholder={'This is an advanced mode'}/>
</Form.Group>
<button type={'submit'}>Submit</button>
</Form>
</Fragment>
)
}
}
export default Advance;
In my console.log(). I got proxy object and onSubmit object. I could not find any of my input there. Then I have no idea how can I dispatch my value to axios
Question:
How to POST file from form to endpoint
<input type="file" onChange={ (e) => this.handleChange(e.target.files) } />
You need to use onChange event to get the file data.
handleChange(selectorFiles: FileList)
{
console.log(selectorFiles);
}
Then you need to get the file info inside the method

Redux form props & typescript

Was looking for years, didn't find anything worthy tho.
When I was working with flow, I could simply:
import { type FieldProps, FormProps } from 'redux-form';
Is there a similar (and that easy) way to properly set props to redux form in typescript?
Docs aren't saying anything about typescript, there's only a page for Flow typings.
However, I found that I can import something like propTypes from redux-form:
import { reduxForm, propTypes } from 'redux-form'
However - redux-form has nothing like propTypes exported, so docs are kinda deprecated.
Link: https://redux-form.com/7.2.1/docs/api/props.md/
Thanks in advance for any kind of help.
tl;dr class RegistrationForm extends React.PureComponent<any> {
what to drop here ^^^^^
You need to install the #types/redux-form package with your package manager. The #types/redux-form package includes types definitions for redux-form package.
Then you can import type definitions from redux-form, for example InjectedFormProps.
Your form that will be wrapped with reduxForm() should has props that extends InjectedFormProps<FormData = {}, P = {}>.
reduxForm() type is generic reduxForm<FormData = {}, P = {}>(...
See the example:
import * as React from 'react';
import { reduxForm, InjectedFormProps, Field } from 'redux-form';
import { IUser } from './index';
interface IProps {
message: string;
}
class UserForm extends React.Component<InjectedFormProps<IUser, IProps> & IProps> {
render() {
const { pristine, submitting, reset, handleSubmit, message } = this.props;
return (
<form onSubmit={handleSubmit}>
<div>{message}</div>
<div>
<label>First Name </label>
<Field
name="firstName"
component="input"
type="text"
placeholder="First Name"
/>
</div>
<div>
<label>Last Name </label>
<Field
name="lastName"
component="input"
type="text"
placeholder="Last Name"
/>
</div>
<div>
<button type="submit" disabled={pristine || submitting}>
Submit
</button>
<button type="button" disabled={pristine || submitting} onClick={reset}>
Clear Values
</button>
</div>
</form>
);
}
}
export default reduxForm<IUser, IProps>({
form: 'userForm',
})(UserForm);
The source code of #types/redux-form package is located here. You can see the types there and more complicated examples in the redux-form-tests.tsx file that is used for types checking.

Categories

Resources