How to set a default year datepicker react? - javascript

I am using react datepicker, I would like to set a default year(1990) when the calender is open, tried 'date', 'initialDate' prop but it is not working.
Here is my code :
const defaultYear = new Date("1990-01-01")
<LentoFormikDatePicker
name='date_of_birth'
label='Date of birth'
value={values.date_of_birth}
setFieldValue={setFieldValue}
maxDate={addYearsToDate(-18)}
minDate={addYearsToDate(-100)}
date={defaultYear}
/>

You can use react-date-picker and the sample working code for the functionality you asked is given below:
Sample Code
import React, { useState } from "react";
import logo from './logo.svg';
import './App.css';
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
function App() {
// const defaultYear = new Date("1990-01-01")
const [defaultYear, setdefaultYear] = useState(new Date("1990-01-01"));
return (
<div className="App">
<header className="App-header">
<DatePicker
selected={defaultYear}
name='date_of_birth'
label='Date of birth'
onChange={(date) => setdefaultYear(date)}
// value={values.date_of_birth}
// setFieldValue={setdefaultYear}
// maxDate={addYearsToDate(-18)}
// minDate={addYearsToDate(-100)}
//date={defaultYear}
/>
</header>
</div>
);
}
export default App;
The below urls will help in getting more details about react date-picker.
https://kandi.openweaver.com/javascript/wojtekmaj/react-date-picker

Related

Antd <DatePicker/> if value props is set, and click will be infinite loop

I want to set value in value props <DatePicker>. But if i set value, and if i click the date picker, calendar will be infinite loop to the future.
i have use DefaultValue and value props, but produce same error
import React from "react";
import "./index.css";
import type { DatePickerProps } from "antd";
import { DatePicker, Space } from "antd";
import moment from "moment";
const onChange: DatePickerProps["onChange"] = (date, dateString) => {
console.log(date, dateString);
};
const day = moment();
const format = "DD.MM.YYYY";
const App: React.FC = () => (
<Space direction="vertical">
<DatePicker
onChange={onChange}
format={format}
defaultValue={moment(day)}
/>
</Space>
);
export default App;
You can try here
SANBOX
and the picture is here
PICTURE
i have use DefaultValue and value props, but produce same error.
i have delete DefaultValue and value props and calendar is normal, but i cannot set value from beginning
As per the documentation and the below error from the defaultValue when using moment js shows that the accepted format is day js
Type 'string' is not assignable to type 'Dayjs'.
To resolve above issue of showing date , follow below steps
Import dayjs
Using defaultvalue attribute, assign current date using dayjs
import React from "react";
import "./index.css";
import type { DatePickerProps } from "antd";
import { DatePicker, Space } from "antd";
//import moment from "moment";
import dayjs from "dayjs";
const onChange: DatePickerProps["onChange"] = (date, dateString) => {
console.log(date, dateString);
};
const format = "DD.MM.YYYY";
const App: React.FC = () => (
<Space direction="vertical">
<DatePicker onChange={onChange} format={format} defaultValue={dayjs()} />
</Space>
);
export default App;
Updated the codesandbox for your reference - https://codesandbox.io/s/basic-antd-5-1-7-forked-b87dbv?file=/demo.tsx
Documentation link for reference- https://ant.design/components/date-picker

ReferenceError: React is not defined for context

import './App.css';
import ComponentC from './components/ComponentC';
export const UserContext = React.createContext()
function App() {
return (
<div className="App">
<UserContext.Provider value={"deneme"}>
<ComponentC />
</UserContext.Provider>
</div>
);
}
export default App;
import React from 'react'
import ComponentE from './ComponentE'
function ComponentC() {
return (
<div>
<ComponentE />
</div>
)
}
export default ComponentC
import React from 'react'
import ComponentF from './ComponentF'
function ComponentE() {
return (
<div>
<ComponentF />
</div>
)
}
export default ComponentE
import React from 'react'
import { UserContext } from "../App"
function ComponentF() {
return (
<div>
<UserContext.Consumer>
{
user => {
return <div>User Context value {user}</div>
}
}
</UserContext.Consumer>
</div>
)
}
export default ComponentF
I have error ReferenceError: React is not defined, I don't understand why I am so new in react.js
so i need some help.
Thanks.
You need to actually pull in the React library somehow, with script tags in your HTML page, such as
<script src="https://unpkg.com/react#17/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#17/umd/react-dom.development.js"></script>
I'd suggest reviewing the doc's here: https://reactjs.org/docs/getting-started.html#try-react, for suggestions getting started & getting going.
Please import React element from react like
import './App.css';
import React from 'react'; // add line here
export const UserContext = React.createContext();
function App() {
return (
.....
);
}
export default App;
You forgot to add import React from 'react'; at the top thus the error.

React Context api, I can't get to object from context

I started to learn React, I'm trying to retrieve data from api, the data is an object with the fields of base, date & rates, without any problem I can print and logout base & date but rates which is an object not.
console.log gives undefined, when trying to iterate is obviously that the object does not exist but in DevTools i can see normal data
Thank you for your help and greetings
Context:
export const ExchangeProvider = props => {
const [lastestExchanges, setLastestExchanges] = useState({})
const fetchLastestExchange = async () => {
try {
await fetch(`https://api.exchangeratesapi.io/latest`).then(data => data.json()).then(data => setLastestExchanges(data))
} catch (err) {
console.log(err)
}
}
useEffect(() => {
fetchLastestExchange()
}, [])
return (
<ExchangeContext.Provider value={[lastestExchanges, setLastestExchanges]}>
{props.children}
</ExchangeContext.Provider>
)
}
Usage:
import React, {useState, useContext} from "react";
import {ExchangeContext} from "../ExchangeContext";
function HomeView() {
const [lastestExchange, setLastestExchange] = useContext(ExchangeContext)
console.log(lastestExchange)
return (
<div className="container">
<p>{lastestExchange.base}</p>
<p>{lastestExchange.date}</p>
{/*<p>{lastestExchange.rates['PLN']}</p>*/}
<ul>
{/*{Object.keys(lastestExchange.rates).map(key => <li>{lastestExchange.rates[key]}</li>)}*/}
</ul>
</div>
)
}
export default HomeView
Provider usage:
import React from 'react';
import HomeView from "./Views/HomeView";
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
import {ExchangeProvider} from "./ExchangeContext";
function App() {
return (
<ExchangeProvider>
<div className="App container w-full flex h-full">
<Router>
<Switch>
<Route path="/">
<HomeView/>
</Route>
</Switch>
</Router>
</div>
</ExchangeProvider>
);
}
export default App;
You can use react context simpler like this :
// src/ThemeContext.js
import React from 'react';
const ThemeContext = React.createContext(null);
export default ThemeContext;
// src/ComponentA.js
import React from 'react';
import ThemeContext from './ThemeContext';
const A = () => (
<ThemeContext.Provider value="green">
<D />
</ThemeContext.Provider>
);
// src/ComponentD.js
import React from 'react';
import ThemeContext from './ThemeContext';
const D = () => (
<ThemeContext.Consumer>
{value => (
<p style={{ color: value }}>
Hello World
</p>
)}
</ThemeContext.Consumer>
);

How can Enzyme check for component visibility?

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

React/Redux Changing Webpage language

I'm making a website that have a functionality to change languages from the homescreen, I'm using Redux to handle the state.
I keep getting TypeError: Cannot read property 'connect' of undefined, and It seems to be from Home.js, I dont know why it happens!!, Please Help !!!
import React, { Component } from 'react';
import ReactRedux from 'react-redux';
import './Home.css';
import Navbar from '../../Reusable/Navbar/Navbar.js';
import Footer from '../../Reusable/Footer/Footer.js';
import Action from '../../Reusable/Action/Action.js';
import ProjectsCarousel from '../../Reusable/ProjectsCarousel/ProjectsCarousel.js';
import Getintouch from '../../Reusable/Getintouch/Getintouch.js';
import Header from './Header/Header.js';
import Info from './Info/Info.js';
import Whyus from './Whyus/Whyus.js';
import Testimonial from './Testimonial/Testimonial.js';
let actions = require('../../../actions');
class Home extends Component {
render() {
const content = this.props.content;
const switchLanguage = this.props.switchLanguage;
if (content){
return (
<div className="home">
<Action />
<Navbar data={content.page.menu} switchLanguage={switchLanguage}/>
<Header />
<Info data={content.page.home}/>
<ProjectsCarousel />
<Whyus />
<Testimonial />
<Getintouch />
<Footer />
</div>
)
} else {
return;
}
}
}
module.exports = ReactRedux.connect(
(state) => ({content: state.content}),
(dispatch) => ({switchLanguage: (lang) => dispatch(actions.switchLanguage(lang))})
)(Home);
export default Home;
That's because react-redux has only named exports.
change your import to:
import * as ReactRedux from 'react-redux';
which will import every named property to ReactRedux Object. or import it like:
import { connect } from 'react-redux';
export default connect(
(state) => ({content: state.content}),
(dispatch) => ({switchLanguage: (lang) => dispatch(actions.switchLanguage(lang))})
)(Home);

Categories