Managing the form properties of a redux-form enhanced with material-ui styling

I am currently working on creating a login form that makes an API call to retrieve a token. As someone new to react and redux, I followed the steps outlined in this tutorial to achieve this.

The login form utilizes redux-form. Below is the code snippet for reference:

login.js

import React, { Component } from 'react';  
import { connect } from 'react-redux';  
import { Field, reduxForm } from 'redux-form';  
import { loginUser } from '../../actions/index';

const form = reduxForm({  
  form: 'login'
});

class Login extends Component {  
  handleFormSubmit(formProps) {
    this.props.loginUser(formProps);
  }

  renderAlert() {
    if(this.props.errorMessage) {
      return (
        <div>
          <span><strong>Error!</strong> {this.props.errorMessage}</span>
        </div>
      );
    }
  }

  render() {
    const { handleSubmit } = this.props;

    return (
      <div>
        <form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
        {this.renderAlert()}
        {/* {this.renderAlert.bind()} */}
          <div>
            <label>Username</label>
            <Field name="username" component="input" type="text" />
          </div>
          <div>
            <label>Password</label>
            <Field name="password" component="input" type="password" />
          </div>
          <button type="submit">Login</button>
        </form>
      </div>
    );
  }
}

function mapStateToProps(state) {  
  return {
    errorMessage: state.auth.error,
    message: state.auth.message
  };
}

export default connect(mapStateToProps, { loginUser })(form(Login));

After successfully implementing the login functionality, I decided to integrate Material Ui to enhance the visual design of the form fields.

// input basic version
<Field name="username" component="input" type="text" />
// material-ui version 
<Field name="username" component={TextField} type="text" />

However, after making this change, the props (username, password) are not being passed to the handleFormSubmit function, causing issues with the API call to log in the user. I am seeking assistance to resolve this issue.

Answer №1

To seamlessly integrate data from the props provided by redux-form into a material-ui component, you will need to create a translation layer as explained in the documentation for redux-form found here.

If you are working with a TextField, your function would resemble this:

const renderTextField = ({
  input,
  label,
  meta: { touched, error },
  ...custom
}) => (
  <TextField
    hintText={label}
    floatingLabelText={label}
    errorText={touched && error}
    {...input}
    {...custom}
  />
)

Next, you will use this function as the component for the Field:

<Field name="username" component={renderTextField} />

Alternatively, you can utilize a library that provides pre-made wrappers for ease of use, such as redux-form-material-ui.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be the reason for the malfunctioning of my React Native vector icons?

My react native vector icons are not working despite following all the steps mentioned in the documentation. I am unable to use a camera icon in my app. I tried importing { Entypo } from 'react-native-vector-icons'; and then using \<Entyp ...

Storing user-submitted files like images, PDFs, and PNGs into a database using ReactJS

I am currently in the process of developing an application that allows users to easily share files with each other by uploading them to their profiles. In order to achieve this, I have created a component called AddReport which sets up initial states for ...

What is causing the issue with using transition(myComponent) in this React 18 application?

Recently, I have been immersed in developing a Single Page Application using the latest version of React 18 and integrating it with The Movie Database (TMDB) API. My current focus is on enhancing user experience by incorporating smooth transitions between ...

Problem with Angular Material Sidenav Styling

Currently, I am working with the mat-sideNav route and encountered a CSS issue with the sidenav after selecting a new route. When I click on a new route using the sidenav module and then return to the sidenav to change routes again, I notice that the hover ...

Transforming an Input Field into a String with React's onChange Event

I have a small application consisting of three components Parent Component: App Son Component: Courses Grandchild Component: Course The state of the app is stored in the App component. In the Course component, there is an input field with an onChange ev ...

"Want to display a filter for a specific column in a Material UI React table? Here's

Is there a way to display the filter option only for specific columns, such as First Name, without it appearing on other columns like Id, Last Name, and Full Name? https://i.stack.imgur.com/HdBcp.png import React, { useEffect, useState } from "react& ...

Creating a background with image overlays in React: A step-by-step guide

My challenge is to have an image that covers the entire background but it seems to stop abruptly where another object is placed, unable to extend further. I am utilizing Material UI and here is a snippet of my code: import { Image } from "../images&q ...

When Express serves a React build, the webpage displays as blank

My current project structure looks like this: app server.js frontend build index.html The build directory is the result of running npm run build in my React app (created using create-react-app). There are additional files but I will exclude them ...

The validation feature is ineffective when used with Material UI's text input component

I need a function that can validate input to make sure it is a number between 1 and 24. It should allow empty values, but not characters or special symbols. function handleNumberInput(e) { const re = /^[0-9\b]+$/; const isNumber = re.test(e.target.val ...

MUI: (Autocomplete) The input given for Autocomplete is not valid

While attempting to load data into an MUI Autocomplete, I encountered this message in the console. React-hook-form and yup are being used for form validation. Image displaying the warning To showcase my issue, I have set up a CodeSandbox. In this example, ...

React component that displays a dropdown menu with options ranging from 1 to n

My current select dropdown displays numbers from 1 to 10 as shown below: const options = [ { label: 1, value: 1 }, { label: 2, value: 2 }, { ...

What is the best way to create mock icons for all the React `@material-ui/icons` using Jest?

Can this query be broadened to ask - what is the best way to simulate all attributes on a module that has been imported in order to produce React components? ...

Tips for aggregating the values of object arrays in React props

I need help sorting three top-rated posts. Currently, the function displays three post titles along with their ratings, but they are not sorted by best rating. Can anyone assist me with this issue? {posts.slice(0, 3).sort((a, b) => ...

Is there a way to create a unique link to the author in Spfx/React and SharePoint 2019?

I have recently started working with Sharepoint (2019) & React and I have a question: My objective is to create a webpart that presents entries from a list in a more visually appealing way. Initially, I retrieved all the items from the list using the ...

Is there a material button available for use in Java programming?

Is it possible to integrate Material UI into a Java application? I am currently developing a calculator using Swing and AWT in Eclipse, and I'm interested in incorporating Material Design elements such as the material button. Has anyone successfully ...

Manage the material-ui slider using play and pause buttons in a React JS application

I have a ReactJS project where I am utilizing the continuous slider component from material-ui. My goal is to be able to control the slider's movement by clicking on a play button to start it and stop button to halt it. Below is the code snippet of th ...

Tutorial on how to update a specific value in an array of objects using setState on click event

I need to toggle the active class on click, setting it to a local state and changing all other objects in the state to inactive. const [jobType, setJobType] = useState([ { "class": "active", "type& ...

Tips for ensuring that Breadcrumbs are displayed properly with the noWrap feature

I am currently working on making the MUI component Breadcrumbs responsive. The issue I am facing is that when the Breadcrumbs component fills up all available space, the items shrink and use ellipsis like a Typography component with the noWrap property se ...

Is it possible that a declaration file for module 'material-ui/styles/MuiThemeProvider' is missing?

I have been trying to implement the react material-ui theme after installing it via npm. However, I am encountering errors when adding 'import MuiThemeProvider from "material-ui/styles/MuiThemeProvider";' in boot-client.tsx: TS7016: Could not ...

React Material-UI - Mobile-friendly Masonry Layout

I'm new to working with React and I'm currently exploring how to create a Masonry image grid that is responsive for mobile devices. The goal is to have the images stack on top of each other in mobile view while maintaining the classic Masonry gri ...