I have a problem I can't deal with. In a project I'm working on, when I click on a colour, the colour of the t-shirt should change, but in the meantime I get an error. I really need help. Repo to project: https://github.com/ewaolczak/product-personalizer/commit/a70ad00e360bc96de28c32e27c9c8ee9b9626a6a?w=1
I have read the course material several times, searched for solutions on the Internet and still do not know where the error is.
CodePudding user response:
On line 25 of OptionColor.js
, you try accessing setCurrentColor()
from props, which is likely where the error is thrown. This is because on line 73 of Product.js
, where the <OptionColor>
component is used, you don't pass in a prop named "setCurrentColor" equal to a function.
To fix this, I think what you meant to do on line 73 of Product.js
is:
<OptionColor colors={props.colors} setCurrentColor={setCurrentColor} />
CodePudding user response:
In your file OptionColor.js you are calling props.setCurrentColor(color)
. That function does not exist, because the parent has not got the prop defined.
In your Product.js file, add the following:
<OptionColor
colors={props.colors}
setCurrentColor={setCurrentColor}
/>
CodePudding user response:
Why there is an error:
In your OptionColor
component, the code describes that whenever the button is clicked, it will call props.setCurrentColor(whatever-color)
like so:
<button onClick={() => props.setCurrentColor(color)}></button>
This is telling React to call the setCurrentColor
argument passed into the component. The problem is, your Product
component doesn't pass in a setCurrentColor
function, just the colors
array.
<OptionColor colors={props.colors} />
To fix:
Change the OptionColor
usage in the Product
component to:
<OptionColor colors={props.colors} setCurrentColor={setCurrentColor} />
To provide the OptionColor
a way to change its parent's state.
CodePudding user response:
This is your OptionColor.js:
import React from 'react';
import styles from './OptionColor.module.scss';
import shortid from 'shortid';
import clsx from 'clsx';
const OptionColor = (props) => {
const prepareColorClassName = (color) => {
return styles[
'color' color[0].toUpperCase() color.substr(1).toLowerCase()
];
};
return (
<div className={styles.colors}>
<h3 className={styles.optionLabel}>Colors</h3>
<ul className={styles.choices}>
{props.colors?.map((color) => (
<li key={shortid()}>
<button
type='button'
className={clsx(
prepareColorClassName(color),
props.currentColor === color ? styles.active : undefined
)}
onClick={() => props.setCurrentColor(color)}></button>
</li>
))}
</ul>
</div>
);
}
export default OptionColor;
At the bottom in your <li>
is this line, which is trying to call a setCurrentColor
. This function was was not passed to the component (it's undefined):
onClick={() => props.setCurrentColor(color)}></button>
Solution
In Product.js, change:
<OptionColor colors={props.colors} />
To:
<OptionColor colors={props.colors} setCurrentColor={setCurrentColor} />