I'm new to React and I'm trying to incorporate viewSwitching from https://devexpress.github.io/devextreme-reactive/react/scheduler/docs/guides/view-switching/ into my project. The issue I'm facing is that this view has class components and I've written my code in functional components, is there any way to implement the code given below into functional components so that viewSwitching may work?
import * as React from 'react';
import Paper from '#material-ui/core/Paper';
import { ViewState } from '#devexpress/dx-react-scheduler';
import {
Scheduler,
WeekView,
Appointments,
Toolbar,
ViewSwitcher,
MonthView,
DayView,
} from '#devexpress/dx-react-scheduler-material-ui';
import { appointments } from '../../../demo-data/month-appointments';
export default class Demo extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
data: appointments,
currentViewName: 'work-week',
};
this.currentViewNameChange = (currentViewName) => {
this.setState({ currentViewName });
};
}
render() {
const { data, currentViewName } = this.state;
return (
<Paper>
<Scheduler
data={data}
height={660}
>
<ViewState
defaultCurrentDate="2018-07-25"
currentViewName={currentViewName}
onCurrentViewNameChange={this.currentViewNameChange}
/>
<WeekView
startDayHour={10}
endDayHour={19}
/>
<WeekView
name="work-week"
displayName="Work Week"
excludedDays={[0, 6]}
startDayHour={9}
endDayHour={19}
/>
<MonthView />
<DayView />
<Toolbar />
<ViewSwitcher />
<Appointments />
</Scheduler>
</Paper>
);
}
}
Any help at all will be appreciated :)
import * as React from 'react';
import Paper from '#material-ui/core/Paper';
import { ViewState } from '#devexpress/dx-react-scheduler';
import {
Scheduler,
WeekView,
Appointments,
Toolbar,
ViewSwitcher,
MonthView,
DayView,
} from '#devexpress/dx-react-scheduler-material-ui';
import { appointments } from '../../../demo-data/month-appointments';
const Demo = () => {
const [state, setState] = useState({
data: appointments,
currentViewName: 'work-week'
})
const currentViewNameChange = (currentViewName) => {
setState({ currentViewName });
};
return (
<Paper>
<Scheduler
data={state.data}
height={660}
>
<ViewState
defaultCurrentDate="2018-07-25"
currentViewName={state.currentViewName}
onCurrentViewNameChange={currentViewNameChange}
/>
<WeekView
startDayHour={10}
endDayHour={19}
/>
<WeekView
name="work-week"
displayName="Work Week"
excludedDays={[0, 6]}
startDayHour={9}
endDayHour={19}
/>
<MonthView />
<DayView />
<Toolbar />
<ViewSwitcher />
<Appointments />
</Scheduler>
</Paper>
);
}
export default Demo;
Just update state and function like this
const Demo = (props) => {
const [data, useData] = useState(appointments);
const [currentViewName, setCurrentViewName] = useState("work-week");
const currentViewNameChange = (currentViewName) => {
setCurrentViewName(currentViewName);
};
return (
<Paper>
<Scheduler data={data} height={660}>
<ViewState
defaultCurrentDate="2018-07-25"
currentViewName={currentViewName}
onCurrentViewNameChange={currentViewNameChange}
/>
<WeekView startDayHour={10} endDayHour={19} />
<WeekView
name="work-week"
displayName="Work Week"
excludedDays={[0, 6]}
startDayHour={9}
endDayHour={19}
/>
<MonthView />
<DayView />
<Toolbar />
<ViewSwitcher />
<Appointments />
</Scheduler>
</Paper>
);
};
Related
i want to share props from components to sibling children. I've read about React Context but can't implement it.
My home component looks like this:
const Home = () => {
return (
<>
<Navigation />
<SearchBar />
<Wrapper>
<Filters />
<ProductsList />
</Wrapper>
</>
);
}
I have search state in SearchBar component, and need to pass it to ProductList component
const [search, setSearch] = useState('');
const handleSetSearch = (e) => {
setSearch(e.target.value);
}
return (
<Wrapper>
<StyledTitle>inPal Search</StyledTitle>
<InputWrapper>
<StyledInput type="text" placeholder="Write something..." onChange={(e) => handleSetSearch(e)} />
<SearchIcon src={searchIcon} alt="Search" />
</InputWrapper>
</Wrapper>
);
Can someone help me to understand this?
You can declare the state in parent component (Home) and pass it as prop to both the child components as:
const Home = () => {
const [search, setSearch] = useState('');
return (
<>
<Navigation />
<SearchBar search={search} setSearch={setSearch} />
<Wrapper>
<Filters />
<ProductsList search={search} />
</Wrapper>
</>
);
}
import React, { createContext } from "react";
import ProductsList from "./ProductsList";
const [search, setSearch] = useState('');
const handleSetSearch = (e) => {
setSearch(e.target.value);
}
const Sr = createContext();
return (
<Wrapper>
<StyledTitle>inPal Search</StyledTitle>
<InputWrapper>
<StyledInput type="text" placeholder="Write something..." onChange={(e) => handleSetSearch(e)} />
<SearchIcon src={searchIcon} alt="Search" />
</InputWrapper>
<Sr.Provider value={search}>
<ProductsList/>
</Sr.Provider>
</Wrapper>
);
ProductList
import React, { useContext } from "react";
import { Sr } from "./App";
const ProductList = () => {
const sr = useContext(Sr);
return <h1> your value is here {sr} </h1>
}
I am working on an app with React and Redux and displaying some data from API in TextInput control. But now I am not able to edit the data in the TextInput. Following is my complete code of the class:
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import Article from "grommet/components/Article";
import Box from "grommet/components/Box";
import Button from "grommet/components/Button";
import Header from "grommet/components/Header";
import Heading from "grommet/components/Heading";
import Section from "grommet/components/Section";
import AdminMenu from "../../components/Nav/Admin";
import NavControl from "../../components/Nav/Control";
import { getMessage } from "grommet/utils/Intl";
import Notices from "../../components/Notices";
import CheckBox from "grommet/components/CheckBox";
import TextInput from "grommet/components/TextInput";
import { pageLoaded } from "../utils";
import {
recognitionSettingsLoaded,
recognitionSettingsSaved,
} from "../../actions/settings-recognition";
import dashboard from "../../reducers/dashboard";
class Settings extends Component {
constructor(props) {
super(props);
this.handleDaysChange = this.handleDaysChange.bind(this);
this.handleActiveChange = this.handleActiveChange.bind(this);
}
componentDidMount() {
const { dispatch, settingRecognition } = this.props;
console.log(this.props.state);
console.log(dashboard);
dispatch(recognitionSettingsLoaded("2"));
pageLoaded("Configuration");
}
onSave() {
const { survey, dispatch } = this.props;
dispatch(
recognitionSettingsSaved(
this.props.settingRecognition.days,
this.props.settingRecognition.active
)
);
}
handleDaysChange(e) {
const days = e.target.value;
settingRecognition.days = days;
}
handleActiveChange(e) {
const active = e.target.value;
settingRecognition.active = active;
}
render() {
const { dispatch, settingRecognition } = this.props;
console.log("render method");
console.log(settingRecognition);
const { intl } = this.context;
return (
<Article primary={true}>
<Header
direction="row"
justify="between"
size="large"
pad={{ horizontal: "medium", between: "small" }}
>
<NavControl name={getMessage(intl, "Configuration")} />
<AdminMenu />
</Header>
<Box pad={{ horizontal: "medium", vertical: "medium" }}>
<Heading tag="h4" margin="none">
{getMessage(intl, "RecognitionLifetime")}
</Heading>
<Heading tag="h5" margin="none">
{getMessage(intl, "DefineIsRecognitionTemporary")}
</Heading>
<Box direction="row">
<CheckBox
toggle={true}
checked={settingRecognition.active}
onChange={this.handleActiveChange}
/>{" "}
<Heading tag="h3" margin="none">
{getMessage(intl, "NewUserActive")}
</Heading>
</Box>
<Heading tag="h3" margin="none">
{getMessage(intl, "HideAfter")}
</Heading>
<Box direction="row">
<TextInput
placeholder="type here"
value={settingRecognition.days.toString()}
onChange={this.handleDaysChange}
/>{" "}
<Heading tag="h3" margin="none">
{getMessage(intl, "Days")}
</Heading>
</Box>
<Button
path="/recognition-settings"
label={getMessage(intl, "NewUserSave")}
primary={true}
onClick={() => {
this.onSave();
}}
/>
</Box>
<Notices />
</Article>
);
}
}
Settings.propTypes = {
dispatch: PropTypes.func.isRequired,
settingRecognition: PropTypes.object.isRequired,
};
Settings.contextTypes = {
intl: PropTypes.object,
};
const mapStateToProps = (state) => ({
settingRecognition: state.settingRecognition,
});
export default connect(mapStateToProps)(Settings);
I have created handleDaysChange function which should run on the text change of TextInput control. I have done similar thing for the checkbox and that works fine but I am not able to get it working for the TextInput.
You are not binding your change events.
Try this....
class Settings extends Component {
constructor(props){
super(props);
this.handleDaysChange = this.handleDaysChange.bind(this);
this.handleActiveChange = this.handleActiveChange.bind(this);
}
componentDidMount(){
....
}
......
}
and change this
<CheckBox
toggle={true}
checked={settingRecognition.active}
onChange={(e) => this.handleActiveChange(e)}
/>
To this
<CheckBox
toggle={true}
checked={settingRecognition.active}
onChange={this.handleActiveChange}
/>
same for text input
<TextInput
placeholder="type here"
value={settingRecognition.days.toString()}
onChange={this.handleDaysChange}
/>
You need to set up two-way-binding so that the content of the textInput reflects the prop that you set in your onChange function. Try giving your textInput a property of value={this.settingRecognition.days}
I am trying to display different Components when I click a button with my OnClick in the Render Function of my App.js.
I would like to show a certain component when the button is clicked and it hides the other components.
this is an example of what I want to do
return (
<div className={styles.container}>
<img className={styles.image} src={image} alt="COVID-19" />
//If the Country Button which is the default is clicked show This
<ThemeProvider theme = {theme}>
<CountryPicker handleCountryChange={this.handleCountryChange} />
<CountryCards CountryData = {CountryData} CountryYesterdayData = {CountryYesterdayData}/>
</ThemeProvider>
<Chart countrydailydata ={countrydailydata} />
//If the State Button is clicked show this
<ThemeProvider theme= {theme}>
<StatePicker handleStateChange={this.handleStateChange} />
<StateCards stateData= {stateData} yesterdayStateData = {yesterdayStateData}/>
</ThemeProvider>
//If the City Button is clicked show this
<CityPicker handleCityChange={this.handleCityChange}/>
<CityCard cityData = {cityData}/>
</div>
);
import React from 'react';
import logo from './logo.svg';
import './App.css';
function Statepicker(){
return(
<div>Statepicker</div>
)
}
function Statecards(){
return(
<div>Statecards</div>
)
}
function Countrypicker(){
return(
<div>Countrypicker</div>
)
}
function Countrycards(){
return(
<div>Countrycards</div>
)
}
class ThemeProvider extends React.Component{
constructor(props){
super(props);
this.state={country:true,states:false}
}
renderCountryOrState=()=>{
if(this.state.states){
return(<React.Fragment>
<Statepicker/>
<Statecards/>
</React.Fragment>)
}
return (
<React.Fragment>
<Countrypicker/>
<Countrycards/>
</React.Fragment>
)
}
render(){
return(
<div>
<button onClick={(e)=>{this.setState({country:true,states:false})}}>Select country</button>
<button onClick={(e)=>{this.setState({country:false,states:true})}}>Select state</button>
{this.renderCountryOrState()}
</div>
)
}
}
function App() {
return (
<ThemeProvider/>
);
}
export default App;
import React from "react";
import { Button, View } from "react-native";
import styles from "./App.module.css";
import {View} from 'react-native'
import image from "./images/covid1.png";
class App extends React.Component {
constructor(props){
super(props);
state = {
CityButton: false,
StateButton: false,
CountryButton: false
};
}
render() {
{ CountryButton, StateButton, CityButton } = this.state;
return (
<view>
<div className={styles.container}>
<img className={styles.image} src={image} alt="COVID-19" />
<Button title="Country Mode" onPress={() =>
this.setState({CountryButton: true}
)} />
<Button title="State Mode" onPress={() =>
this.setState({StateButton: true}
)} />
<Button title="County Mode" onPress={() =>
this.setState({CityButton: true}
)} />
{CountryButton && <div> Hello </div>}
{StateButton && <div> Hello </div>}
{CityButton && <div> Hello </div>}
</div>
</view>
);
}
}
export default App;
I want to navigate to another screen (i.e 'Details') when I hit the login button. This is my working main code: (could be checked on Snack Expo)
import React, { Component } from 'react';
import { Container, Header, Left, Body, Right, Button, Title, Text, Form, Item, Input, Label} from 'native-base';
import { StackNavigator } from 'react-navigation';
import { DrawerNavigator } from "react-navigation";
export default class Login extends Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: '',
};
}
render() {
return (
<Container>
<Text >Instaride</Text>
<Form>
<Item floatingLabel>
<Label onChangeText={(text) => this.setState({username: text})}>Username</Label>
<Input
value={this.state.username}
onChangeText={username => this.setState({ username })}
placeholder={'Username'}
/>
</Item>
<Item floatingLabel last>
<Label >Password</Label>
<Input
value={this.state.password}
onChangeText={password => this.setState({ password })}
placeholder={'Password'}
secureTextEntry={true}
/>
</Item>
</Form>
<Left>
<Button >
<Text>Login</Text>
</Button>
<Text >Forgot Password?</Text>
</Left>
<Right>
<Button hasText transparent>
<Text>Sign Up Here</Text>
</Button>
</Right>
</Container>
);
}
}
class DetailsScreen extends React.Component {
render() {
return (
<Text>Details Screen</Text>
);
}
}
class RegisterationScreen extends React.Component {
render() {
return (
<Text>sign up time</Text>
);
}
}
However, I get an error when I add this:
const HomeScreenRouter = DrawerNavigator(
{
Home: { screen: Login },
Chat: { screen: DetailsScreen },
Profile: { screen: RegisterationScreen }
}
)
I can not really figure out a way to combine all of these:
onPress={() => this.props.navigation.navigate("Details")}
Also, what exactly should I be exporting at the end of the code?
You should do something like this to work...
import React, { Component } from 'react';
import { Container, Header, Left, Body, Right, Button, Title, Text, Form, Item, Input, Label} from 'native-base';
import { StackNavigator } from 'react-navigation';
import { DrawerNavigator } from "react-navigation";
import { createAppContainer } from 'react-navigation';
class Login extends Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: '',
};
}
render() {
return (
<Container>
<Text >Instaride</Text>
<Form>
<Item floatingLabel>
<Label onChangeText={(text) => this.setState({username: text})}>Username</Label>
<Input
value={this.state.username}
onChangeText={username => this.setState({ username })}
placeholder={'Username'}
/>
</Item>
<Item floatingLabel last>
<Label >Password</Label>
<Input
value={this.state.password}
onChangeText={password => this.setState({ password })}
placeholder={'Password'}
secureTextEntry={true}
/>
</Item>
</Form>
<Left>
<Button >
<Text>Login</Text>
</Button>
<Text >Forgot Password?</Text>
</Left>
<Right>
<Button hasText transparent>
<Text>Sign Up Here</Text>
</Button>
</Right>
</Container>
);
}
}
class DetailsScreen extends React.Component {
render() {
return (
<Text>Details Screen</Text>
);
}
}
class RegisterationScreen extends React.Component {
render() {
return (
<Text>sign up time</Text>
);
}
}
const HomeScreenRouter = createStackNavigator(
{
Details: { screen: Details },
}
)
export default createAppContainer(HomeScreenRouter);
I found so long, but I couldn't solve this problem.
I followed the document they provided, but I can't edit the informations!
The react-admin is not requesting to the backend server. Backend code is perfect, I tested with postman.
Here's the code that has problems.
//Admin.jsx
import React, { Component } from "react";
import { Admin, Resource, EditGuesser, fetchUtils } from "react-admin";
import restProvider from "ra-data-simple-rest";
import { UserList, UserEdit, UserCreate } from "../components/AdminPages/Users";
import userip from "public-ip";
const v4 = async () => {
setTimeout(async () => {
await userip.v4();
}, 300);
};
const httpClient = async (url, options = {}) => {
if (!options.headers) {
options.headers = new Headers({ Accept: "application/json" });
}
// add your own headers here
options.headers.set(
"x-access-token",
sessionStorage.getItem("token") || "null"
);
options.headers.set("x-access-userip", await v4());
return fetchUtils.fetchJson(url, options);
};
const dataProvider = restProvider("http://localhost:4000/data", httpClient);
const AdminPage = () => (
<Admin dataProvider={dataProvider}>
<Resource
name="users"
list={UserList}
edit={UserEdit}
create={UserCreate}
/>
</Admin>
);
export default AdminPage;
//Users.jsx
import React, { Component } from "react";
import {
List,
Datagrid,
TextField,
BooleanField,
EditButton,
ArrayField,
SingleFieldList,
ChipField,
Edit,
SimpleForm,
TextInput,
BooleanInput,
ArrayInput,
SimpleFormIterator,
Create,
translate,
Toolbar,
SaveButton,
Update,
DateField,
DateInput
} from "react-admin";
export const UserList = props => (
<List {...props} title="유저 정보">
<Datagrid rowClick="edit">
<TextField source="id" />
<TextField source="name" />
<TextField source="credit" />
<TextField source="point" />
<TextField source="accumulatedAmount" />
<TextField source="memberLevel" />
<BooleanField source="isAdmin" />
<ArrayField source="boughtProduct">
<SingleFieldList>
<ChipField source="product" />
</SingleFieldList>
</ArrayField>
<EditButton />
</Datagrid>
</List>
);
const UserTitle = ({ record }) => {
return <span>Post {record ? `"${record.id}"` : ""}</span>;
};
export const UserEdit = props => (
<Edit title={<UserTitle />} {...props}>
<SimpleForm>
<TextInput source="id" />
<TextInput source="name" />
<TextInput source="credit" />
<TextInput source="point" />
<TextInput source="accumulatedAmount" />
<TextInput source="memberLevel" />
<BooleanInput source="isAdmin" />
<ArrayInput source="boughtProdut">
<SimpleFormIterator>
<TextInput source="product" />
</SimpleFormIterator>
</ArrayInput>
</SimpleForm>
</Edit>
);
export const UserCreate = props => (
<Create {...props}>
<SimpleForm>
<TextInput source="id" />
<TextInput source="name" />
</SimpleForm>
</Create>
);
If you need more infos, ask me. Thank you.
I think you have a big problem with this feature:
const v4 = async () => {
setTimeout(async () => {
await userip.v4();
}, 300);
};
According to the description, it will return you timeoutID, but not IP:
var timeoutID = scope.setTimeout(function[, delay, arg1, arg2, ...]);
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout
Try this:
<Datagrid>
instead of
<Datagrid rowClick="edit">
under UserList. This is what solved it for me.