Implementing defaultProps in conjunction with withStyles

Currently, I am in the process of developing a component using material-ui withStylers and defaultProps. However, I have encountered an issue where the props of the component are not being retrieved in the styles objects unless they are explicitly passed to the component.

import React from "react";
import PropTypes from "prop-types";
import { withStyles } from "@material-ui/core";

const styles = theme => ({
    ClassTest: {
        anyAttr: props => console.log(props) 
    }
});

const Test = ({classes}) => {
    return (
        <span className={classes.ClassTest}/>
    );
};

Test.defaultProps = {
    val2: "hey"
};

Test.propTypes = {
    val1: PropTypes.bool.isRequired,
    val2: PropTypes.string,
};

export default withStyles(styles, { withTheme: true })(Test);

To use this component, you can do so like this:

<Test val1="Hello">

Expected output in console log:

{
  classes: {...},
  val1: "Hello",
  val2: "hey"
}

However, the actual output is missing the defaultValue for 'val2':

{
  classes: {...},
  val1: "Hello"
}

If you call the component as follows:

<Test val1="Hello" val2="hey">

The output will correctly display both values:

{
  classes: {...},
  val1: "Hello",
  val2: "hey"
}

Shouldn't the styles object automatically retrieve the defaultValue from defaultProps? Am I missing something here?

This development is based on the following versions:

"@material-ui/core": "^4.3.0",
"react": "^16.8.6",

Here is the relevant part of the documentation that I'm referring to:
https://material-ui.com/styles/basics/#adapting-based-on-props

Answer №1

withStyles wraps Test in a higher-order-component and cannot access the default props of Test. The withStyles function adds properties to Test (injects a classes prop), which means that the default props for Test are not known until after withStyles completes its work. For example, if Test had a default prop for classes, it would not be used when withStyles provides

classes</code. However, the default prop would be used when <code>Test
is not wrapped by withStyles.

The code below demonstrates three different approaches:

  1. The first approach you attempted does not work because the default props are not accessible to withStyles.
  2. The second approach applies the default props to the higher-order-component returned by withStyles.
  3. The third approach utilizes makeStyles/useStyles instead of withStyles, allowing the default props to remain on the original component rather than the higher-order-component.

All three approaches function correctly when bgcolor is explicitly specified as "orange", but only approaches 2 and 3 successfully use the default prop value.

(...JavaScript code provided...)

https://codesandbox.io/s/styles-using-defaultprops-f3dfh?fontsize=14

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

Why isn't my Enum functioning properly to display the colored background?

Why isn't the Background Color showing up when I pass in the BGColor Prop dynamically in my next.js + Tailwind app? I have tried passing in the prop for my component, but the color is not appearing. <Title title='This is HOME' descripti ...

Tips for eliminating fade effect during hover in networkD3 chart in R

Currently, I have been exploring the usage examples of networkd3 in r I am curious if there is a way to eliminate the hover effect where everything else fades when hovering over a specific node in the graph. For reference, check out "Interacting with igra ...

Steps for shaping the dialog of Material-UI to fit an image

Is there a way to adjust the size of the dialog box to match that of the image? https://i.stack.imgur.com/pXtXg.png I've also tried changing the background color to transparent without success. https://i.stack.imgur.com/Hjx2x.png ...

Leveraging Selenium for extracting data from a webpage containing JavaScript

I am trying to extract data from a Google Scholar page that has a 'show more' button. After researching, I found out that this page is not in HTML format but rather in JavaScript. There are different methods to scrape such pages and I attempted t ...

Error: In ReactJS, the function this.setState is not recognized as a valid function type

I'm having some trouble setting a property on reselection change. When I try to use this.setState(), it throws an error, even though I have binded onSelectchange in the constructor. EDIT: When I attempt to select all rows from the checkbox in the col ...

Placing an Image in Next.js

I've been trying to position my image all the way to the right of the page using CSS properties like position: absolute and right: 0. I've also attempted setting the parent element's position to relative and the image's position to abso ...

What is the process for extracting the value of a checkbox generated through JavaScript?

I recently came across a helpful post on Stack Overflow that provided sample code demonstrating how to display multiple list of checkboxes dynamically on a dropdown list. The function in the code was exactly what I needed for my webpage. However, I encount ...

Resolving the Enigma: Querying jQuery for Real-Time Validation and

I'm fairly new to jQuery and I'm facing a challenge in my registration form script. Specifically, I want to check if the entered username or email is already taken while the user is typing. Currently, this functionality works by making a json req ...

Typescript Tooltip for eCharts

I'm working on customizing the tooltip in eChart v5.0.2 using Typescript, but I'm encountering an error related to the formatter that I can't seem to resolve. The error message regarding the function keyword is as follows: Type '(param ...

Steps to retrieve values from a grid and execute a sum operation using PROTRACTOR

Embarking on my Protractor and Javascript journey, I am faced with the challenge of writing a test script to retrieve values of various accounts under the header "Revenue" (as shown in the image below). My task involves extracting all number values listed ...

Tips for organizing JSON object data and displaying it appropriately on an HTML page

This code utilizes ajax: $("form").on("submit", function () { var data = { "action": "test" }; data = $(this).serialize() + "&" + $.param(data); $.ajax({ type: "POST", dataType: "json", url: "ajax2.php" ...

The Vite manifest could not find the file "app.jsx" in the resources/js directory. Please run "npm run build

Following the guidelines from , I have successfully created a Laravel application with the following specifications: PHP 8.1.2 Laravel 9.33.0 React During development using VITE (npm run dev), everything works smoothly. However, when attempting to build ...

Is there a built-in constant in the Angular framework that automatically resolves a promise as soon as it

I'm facing a situation where I have code that checks a conditional statement to decide if an asynchronous call should be made. If the condition is not met, the call is skipped. However, I still need to perform some final action regardless of whether t ...

Strategies for combining objects with varying structures on a map

SUMMARY: Looking to merge the data from Students into the corresponding values of Employees, where the value from Students should be included in the same array as Employees['avg_rate' and 'expense']. The updated object array should be ...

Verifying that objects are eligible for garbage collection

My program in node.js receives a high volume of messages. Each time a message is received, I create a new object and pass the message content to it. Inside the constructor of the new object, various operations are performed, including some mongo tasks with ...

Is there a way to simulate the parameters of a method callback from an external dependency in Nodejs

Imagine a scenario where I have the following structure: lib/modules/module1.js var m2 = require('module2'); module.exports = function(){ return { // ... get: function(cb){ m2.someMethod(params, function(error, ...

Incorporated new code into the website, functioning properly, although it appears to keep scrolling endlessly below the footer

My website is experiencing a strange issue where the page seems to keep extending beyond the footer due to some JS code. I am not very familiar with JavaScript and have tried different solutions without success. I have searched extensively online for a so ...

Node.js Binary Search Tree - Error: Identifier Not Found

A program run through node.js has been developed to create a binary search tree with various methods like insert, remove, and print. The program is divided into two separate files: Tree.js, which exports the functions Tree() along with its methods and test ...

Making an Axios request upon clicking a button

Why is the functionality of deleting a quiz from the database not working as expected in the code snippet below, even though it works fine with Postman? deleteQuiz = () => { const quiz = this.state.quizData._id axios.delete(`http://localhost: ...

I wonder what the response would be to this particular inquiry

I recently had an angular interview and encountered this question. The interviewer inquired about the meaning of the following code snippet in Angular: code; <app-main [type]="text"></app-main> ...