in my useState I have object with bunch of values. I have input and setting it's value to useState[key] dynamically it works. but problem occurs when I want to update values.
when I am calling onChange and {...prev,prev[key]:e.target.value} it's not working.
import { useGlobalContext } from '#/context';
import { useEffect } from 'react';
import styles from './Validation.module.css';
function ReusebleForm({fieldType,inputName}) {
const {generalInfo,setGeneralInfo} = useGlobalContext();
function displayInfo(e,iName) {
// this part does not work
setGeneralInfo({...generalInfo,...{generalInfo[`${iName}`]:e.target.value}});
}
useEffect(()=>{},[generalInfo])
return (
<input type={`${fieldType}`} required value={generalInfo[inputName]} name={inputName} onChange={(e) => displayInfo(e,inputName)} />
)
}
export default ReusebleForm
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
this is the state
const [generalInfo,setGeneralInfo] = useState({
name: "a",
surname: "v"
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
The error says that the useState is not defined.
import { useEffect,useState } from 'react';
Try importing the useState and check as shown above
Related
I am new to React and I am learning about the props.
My prop doesn't display color on Events.js
I got "I am a car" and red didn't display.
This is my component Welcome.js :
import React from 'react'
import ReactDOM from "react-dom";
function Welcome(props) {
return <h2>I am a {props.color} Car!</h2>;
}
ReactDOM.render(<Welcome color="red"/>, document.getElementById('root'));
export default Welcome;
my page Events.js:
import React, { useState } from "react";
import Calendar from "react-calendar";
import { render } from "react-dom";
import Form from "./Form";
import Welcome from "./Welcome"
function Events() {
const [date, setDate] = useState(new Date());
return (
<div className='app'>
<Form/>
<Welcome/>
</div>
);
}
export default Events;
You are not setting the prop in Events.js. This means the value of props.color is undefined when the render function is called. undefined within curly braces will be ignored by React.
You can add a guard to ensure that you see an error if the prop is not defined:
function Welcome(props) {
if (props.color == null) {
throw 'color should be defined';
}
return <h2>I am a {props.color} Car!</h2>;
}
I'm trying to reference a React icon through a ref, and attempting to do so yields to error:
Function components cannot be given refs. Attempts to access this ref will fail. Did you
mean to use React.forwardRef()?
Is there any way to work around this? I tried wrapping the icon in a React.forwardRef() to no avail.
import React, { useRef } from 'react'
import { FaChevronDown } from "react-icons/fa"
export default function Dashboard() {
const chevronRef = useRef(null)
const ChevronIconWrapper = React.forwardRef((props, ref) =>(
<FaChevronDown className="icon" ref={ref} />
));
const AccountLabel = () => {
{/* Neither of these seem to work. */}
<FaChevronDown className="icon" ref={chevronRef} />
<ChevronIconWrapper ref={chevronRef}/>
}
return(
<AccountLabel />
)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
I am recently working on a react project which is creating taking the input from the redux-form#8.3.7. But the issue is it is not taking the value in the form.
On checking the redux-dev tool the value is replacing the previous one, I searched for a similar issue throughout the internet could not find a solution for it.
My Code
Reducers
import { combineReducers } from "redux";
import { reducer as formReducer } from 'redux-form'
import ocaFormFieldReducer from "./ocaFormReducers/ocaFormFieldReducer";
import stepperActiveStepReducer from "./ocaFormReducers/stepperActiveStepReducer";
import groupFieldReducer from "./ocaFormReducers/groupFieldReducer";
const reducer = combineReducers({
ocaFormFieldReducer,
stepperActiveStepReducer,
groupFieldReducer,
formReducer
});
export default reducer;
import React from "react";
import { connect } from "react-redux";
import { Field, reduxForm } from "redux-form";
import { withStyles } from "#material-ui/core/styles";
function ProductPlanning(props) {
const { classes, formFieldLoading, formFieldData, handleActiveStep, activeStep, cancelFormProgress, setGroupFieldApiStart, groupFieldData } = props;
return (
<div className={classes.root}>
{formFieldLoading && <LoadingScreen />}
<form>
<Field name="SUrya" component="input" type="text" />
</form>
)
}
export default reduxForm({ form: "ocaFormData" })(connect(mapStateToProps, mapDispatchToProps)(withStyles(styles)(ProductPlanning)));
It would be helpful if you can throw some light on this.
Thank you in advance.
The solution is simple and yet DUMB.
In Combine reducer, the value reducer should have a key-value pair with key name as form.
const reducer = combineReducers({
ocaFormFieldReducer,
stepperActiveStepReducer,
groupFieldReducer,
form: formReducer
});
I've attached a cut down version of an issue I am having. I have a simple Checkbox which I hide using opacity : 0 depending on what is passed into the component containing the Checkbox (in this case MyCheckbox)
MyCheckBox.js
import React from "react";
import "./styles.css";
import { Checkbox, makeStyles } from "#material-ui/core";
const useStyles = makeStyles({
checkboxHiddenStyle: {
opacity: 0
}
});
export default function MyCheckbox(props) {
const styles = useStyles(props);
return (
<div>
<Checkbox
{...props}
className={props.data.length === 0 && styles.checkboxHiddenStyle}
/>
</div>
);
}
I have a component which uses MyCheckbox called MyCheckboxesInUse which results in one checkbox showing and the other being hidden.
How do I check the visibility of each of these in a Jest/Enzyme test ? I've looked at lots of posts but can't find something that works!
Code and test running here on CodeSandbox
MyCheckBoxesInUse.js
import React from "react";
import MyCheckbox from "./MyCheckbox";
import "./styles.css";
export default function MyCheckboxesInUse() {
const arrayWithNothing = [];
const arrayWithSomething = [1];
return (
<div className="App">
<h1>Hidden Checkbox</h1>
<MyCheckbox data={arrayWithNothing} />
<h1>Visible Checkbox</h1>
<MyCheckbox data={arrayWithSomething} />
</div>
);
}
MyCheckbox.test.js
import React from "react";
import Enzyme, { mount } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import MyCheckboxesInUse from "./MyCheckboxesInUse";
import MyCheckbox from "./MyCheckbox";
Enzyme.configure({ adapter: new Adapter() });
test("Check that one checkbox is hidden and the other is visible", () => {
const wrapper = mount(<MyCheckboxesInUse />);
const checkboxes = wrapper.find(MyCheckbox);
expect(checkboxes).toHaveLength(2);
//HOW DO I CHECK THAT ONE IS VISIBLE AND THE OTHER IS NOT ?
});
You can tryout jest-dom from testing-library, but if you want to see how they implement what you want, check out their code: https://github.com/testing-library/jest-dom/blob/master/src/to-be-visible.js
I'm new to stackoverflow and quite new to using react/redux. I've been scanning over quite a few posts already to see if a similar post could provide me with an answer but I'm still left puzzled.
I currently have a presentational component "Repetitions" and a container component to get props from redux store and dispatch actions from the presentational component to redux store. I have the presentational component updating the redux store when I enter data into the input field but I am wanting to use the redux store to retrieve the input value so that when a user first comes on to the page the input value is "0" as that is the initial value inside the redux store.
I originally made a simple Counter component using react/redux and it was working ok. I have since made the "Repetition" component and altered the redux store to use a combinedreducer and this is when the problems seemed to start as neither components can read from the redux store.
Rootreducer.ts
import { combineReducers } from "redux";
import countReducer from "./example/reducer";
import repetitionsReducer from "./reps/reducer";
const rootReducer = combineReducers({
countReducer,
repetitionsReducer
})
export default rootReducer;
RepetitionsReducer.ts
import { RepetitionsState } from "../types";
import { AddRepetitionsAction } from "./actions";
export type RepetitionsActionType = AddRepetitionsAction;
export type Dispatch = (action: RepetitionsActionType) => void;
// The reducer updates the count
const initialState: RepetitionsState = {
repetitions: 0
};
const repetitionsReducer = (
state = initialState,
action: RepetitionsActionType
): RepetitionsState => {
switch (action.type) {
case "ADD_REPETITIONS":
return { ...state, repetitions: action.repetitions };
default:
return state;
}
}
export default repetitionsReducer;
RepetitionsContainer.ts
import { connect } from "react-redux";
import { RootState } from "../../store/types";
import { Dispatch } from "../../store/reps/reducer";
import { addRepetitions } from "../../store/reps/actions";
import Repetitions from "../../components/reps/Repetitions";
interface StateFromProps {
repetitions: number ;
}
interface DispatchFromProps {
updateRepetitions: (repetitions: number) => void;
}
export type RepetitionsProps = StateFromProps & DispatchFromProps;
const mapStateToProps = (state: RootState): StateFromProps => ({
repetitions: state.repetitions
});
const mapDispatchToProps = (dispatch: Dispatch): DispatchFromProps => ({
updateRepetitions: (repetitions: number) => dispatch(addRepetitions(repetitions))
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(Repetitions);
RepetitionsComponent.ts
note: When I try to console.log "repetitions" I am getting undefined at the moment.
import React from "react";
import { RepetitionsProps } from "../../containers/reps/Repetitions";
const Repetitions: React.FunctionComponent<RepetitionsProps> = ({
repetitions,
updateRepetitions
}) => {
console.log(repetitions)
return (
<div>
<h3>Reps</h3>
<input
onChange={(event) => updateRepetitions(Number(event.target.value))}
value={ repetitions } // <-- This is the value i'm wanting to present to the user from the redux store
/>
</div>
);
};
export default Repetitions;
App.ts
import React from "react";
import ReactDOM from "react-dom";
import * as serviceWorker from "./serviceWorker";
import Header from "./components/header/Header";
import { Provider } from "react-redux";
import { createStore } from "redux";
import Counter from "./containers/example/Counter";
import Repetitions from "./containers/reps/Repetitions";
import { composeWithDevTools } from 'redux-devtools-extension';
import rootReducer from "./store/reducer";
const store = createStore(rootReducer, composeWithDevTools());
console.log(store.getState())
function App() {
return (
<div className="App">
<Header title={"Rep count"} />
<Repetitions />
<br />
<br />
<br />
<Counter />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
rootElement
);
The expected results I would be hoping to see would be a "0" presented in the input box underneath the "Reps" header when a user first loads the page. Instead the box is empty but the redux store shows the value for repetitions as "0".
reps-input-desired-results
It is also worth noting that the counter below the input field used to read "0" from the redux store when I first loaded the page however now it is also undefined.
Thank you for taking the time to look at my post. Any help would be greatly appreciated!
Hmmm... something is wrong here:
First of all, your state for repetition is currently holding an object. It should hold a simple number.
Secondly, the name of the repetition state on the store (from the snapshot you've attached) is "repetitionReducer" and not "repetition" as you try to fetch it in mapStateToProps:
const mapStateToProps = (state: RootState): StateFromProps => ({
repetitions: state.repetitions // <- this one here...
});
Hope this helps :)