How to Convert Class components to functional components in React? - reactjs

import React, { PureComponent, Fragment } from 'react';
class Practice extends PureComponent {
state = {
options: [
{
name: 'Select…',
value: null,
},
{
name: 'Rui',
value: 3000,
},
{
name: 'Catla',
value: 3000,
},
{
name: 'Carpio',
value: 3000,
},
{
name: 'Tilapia',
value: 1750,
},
{
name: 'Mrigel',
value: 3000,
},
{
name: 'Pabda',
value: 3500,
},
{
name: 'Koi',
value: 750,
},
],
value: '?',
};
handleChange = (e) => {
this.setState({ value: e.target.value });
};
render() {
const { options, value } = this.state;
return (
<Fragment>
<select onChange={this.handleChange} value={value}>
{options.map(item => (
<option key={item.value} value={item.value}>
{item.name}
</option>
))}
</select>
<p>Oxygen Demand: {value}</p>
</Fragment>
);
}
}
export default Practice;

Use useState to handle state of options and value
Use useCallback to handle change events on select field
Return your rendered JSX
import React, { useCallback, useState } from "react";
function Practice() {
const [options, setOptions] = useState([
{
name: "Select…",
value: null,
},
{
name: "Rui",
value: 3000,
},
{
name: "Catla",
value: 3000,
},
{
name: "Carpio",
value: 3000,
},
{
name: "Tilapia",
value: 1750,
},
{
name: "Mrigel",
value: 3000,
},
{
name: "Pabda",
value: 3500,
},
{
name: "Koi",
value: 750,
},
]);
const [value, setValue] = useState("?");
const handleChange = useCallback((e) => {
setValue(e.target.value);
}, []);
return (
<>
<select onChange={handleChange} value={value}>
{options.map((item) => (
<option key={item.value} value={item.value}>
{item.name}
</option>
))}
</select>
<p>Oxygen Demand: {value}</p>
</>
);
}
export default Practice;

Convert like this:
import React, { useState, PureComponent, Fragment } from 'react';
let Practice = (praps) =>
let [options,soptions] = useState([
{
name: 'Select…',
value: null,
},
{
name: 'Rui',
value: 3000,
},
{
name: 'Catla',
value: 3000,
},
{
name: 'Carpio',
value: 3000,
},
{
name: 'Tilapia',
value: 1750,
},
{
name: 'Mrigel',
value: 3000,
},
{
name: 'Pabda',
value: 3500,
},
{
name: 'Koi',
value: 750,
},
]);
let [value,svalue]=useState('?')
let handleChange = (e) => {
svalue(e.target.value);
};
render() {
return (
<Fragment>
<select onChange={this.handleChange} value={value}>
{options.map(item => (
<option key={item.value} value={item.value}>
{item.name}
</option>
))}
</select>
<p>Oxygen Demand: {value}</p>
</Fragment>
);
} }
export default Practice;

Related

I want to save just value in react-select

I have some trouble with my react-select: When I click 'Submit', it save an object that have both 'value' and 'label' like this:
enter image description here
All I need is when I choose, it's show label list, and when I submit, it save only value. What can I do? Here are my code:
const [mainLang, setMainLang] = useState("");
const mainLangOptions = [
{ value: 'vi', label: 'Vietnamese' },
{ value: 'en', label: 'English' },
{ value: 'zh', label: 'Chinese' },
{ value: 'ja', label: 'Japanese' },
{ value: 'de', label: 'German' },
];
//This is Select part
<Select
onChange={(e) =>setMainLang(e)}
options={mainLangOptions}
/>
You need to set the option value as the mainLangOptions.value and the label as
mainLangOptions.label. By doing that you will display the label as option labels and save the value as the value of option tag. Check out the code below :
import React from "react";
import "./styles.css";
class App extends React.Component {
constructor() {
super();
this.state = {
mainLanguage: ""
};
}
onOptionChangeHandler = (event) => {
this.state.mainLanguage = event.target.value;
console.log(this.state.mainLanguage);
};
render() {
const mainLangOptions = [
{ value: "vi", label: "Vietnamese" },
{ value: "en", label: "English" },
{ value: "zh", label: "Chinese" },
{ value: "ja", label: "Japanese" },
{ value: "de", label: "German" }
];
return (
<div>
<select onChange={this.onOptionChangeHandler}>
<option>Please choose one option</option>
{mainLangOptions.map((option, index) => {
return (
<option value={option.value} key={index}>
{option.label}
</option>
);
})}
</select>
</div>
);
}
}
export default App;
You must use e.target.value inside your setMainLang
<Select onChange={(e) => setMainLang(e.target.value)}>
This should work for your code but if it doesn't work, here is a complete code that I have tested in code sandbox and you can try it.
import React, { useState } from "react";
import { Select } from "#chakra-ui/react";
const Users = () => {
const [mainLang, setMainLang] = useState("");
const mainLangOptions = [
{ value: "vi", label: "Vietnamese" },
{ value: "en", label: "English" },
{ value: "zh", label: "Chinese" },
{ value: "ja", label: "Japanese" },
{ value: "de", label: "German" }
];
return (
<>
<Select onChange={(e) => setMainLang(e.target.value)}>
{mainLangOptions.map((op) => (
<option value={op.value}>{op.label}</option>
))}
</Select>
<h1>{mainLang}</h1>
</>
);
};
export default Users;

Ant Design Dynamic Data does not binds to Select

I am using react for a school project. The dynamic data does not binds to Options from Ant Design, react js. The result is an empty option list. In actual the data comes from an external API. For testing purpose I assigned the data the state variable. The data comes in 2D array, so I am mapping through the data twice.
Result is:
import { useEffect, useState } from "react";
import { Select } from "antd";
const { Option } = Select;
const Complete = () => {
const [list, setPersons] = useState([
[
{
id: 1,
personName: "Owan",
},
{
id: 2,
personName: "More",
},
{
id: 3,
personName: "Jaila",
},
{
id: 4,
personName: "Eerov",
},
],
[
{
id: 5,
personName: "Rell",
},
{
id: 6,
personName: "Juko",
}
]
]);
useEffect(() => {
console.log(list);
}, []);
return (
<Select
showSearch
style={{ width: 200 }}
placeholder="Select a person"
optionFilterProp="children"
filterOption={(input, option) =>
option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}
>
{list.map((l) => {
l.map((person) => {
console.log(person);
<Option value={person.id}>
{person.personName}
</Option>;
});
})}
</Select>
);
};
export default Complete;
You just needed to update small one using ES6 feature here the script to combine 2 dimensional array to single array
{[].concat(...list).map((l) => <Option value={l.id}>{l.personName}</Option>)}
Here the full script:
import { useEffect, useState } from "react";
import { Select } from "antd";
const { Option } = Select;
const Complete = () => {
const [list, setPersons] = useState([
[
{
id: 1,
personName: "Owan",
},
{
id: 2,
personName: "More",
},
{
id: 3,
personName: "Jaila",
},
{
id: 4,
personName: "Eerov",
},
],
[
{
id: 5,
personName: "Rell",
},
{
id: 6,
personName: "Juko",
}
]
]);
useEffect(() => {
console.log(list);
}, []);
return (
<Select
showSearch
style={{ width: 200 }}
placeholder="Select a person"
optionFilterProp="children"
filterOption={(input, option) =>
option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}
>
{[].concat(...list).map((l) => <Option value={l.id}>{l.personName}</Option>)}
</Select>
);
};
export default Complete;
visit live example demo
Try with the following code:
import { useEffect, useState } from "react";
import { Select } from "antd";
const { Option } = Select;
const Complete = () => {
const [list, setPersons] = useState([
[
{
id: 1,
personName: "Owan"
},
{
id: 2,
personName: "More"
},
{
id: 3,
personName: "Jaila"
},
{
id: 4,
personName: "Eerov"
}
],
[
{
id: 5,
personName: "Rell"
},
{
id: 6,
personName: "Juko"
}
]
]);
useEffect(() => {
console.log(list);
}, [list]);
return (
<Select
showSearch
style={{ width: 200 }}
placeholder="Select a person"
optionFilterProp="children"
filterOption={(input, option) =>
option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}
>
{list.map((l) => (
<>
{l.map((person) => (
<Option value={person.id}>{person.personName}</Option>
))}
</>
))}
</Select>
);
};
export default Complete;

How to implement AddAdiditions in React Sematic UI using Hooks?

I want to have a drop down in my application which allows the user to add an item to the dropdown. I am using React Sematic UI.
Sematic UI Dropdown ALlowAdditions
I am new to react hooks and I want to know how I can implement the onChange and onAddition function using hooks.
import React, { Component } from 'react'
import { Dropdown } from 'semantic-ui-react'
const options = [
{ key: 'English', text: 'English', value: 'English' },
{ key: 'French', text: 'French', value: 'French' },
{ key: 'Spanish', text: 'Spanish', value: 'Spanish' },
{ key: 'German', text: 'German', value: 'German' },
{ key: 'Chinese', text: 'Chinese', value: 'Chinese' },
]
class DropdownExampleAllowAdditions extends Component {
state = { options }
handleAddition = (e, { value }) => {
this.setState((prevState) => ({
options: [{ text: value, value }, ...prevState.options],
}))
}
handleChange = (e, { value }) => this.setState({ currentValue: value })
render() {
const { currentValue } = this.state
return (
<Dropdown
options={this.state.options}
placeholder='Choose Language'
search
selection
fluid
allowAdditions
value={currentValue}
onAddItem={this.handleAddition}
onChange={this.handleChange}
/>
)
}
}
export default DropdownExampleAllowAdditions
Any help would be greatly appreciated. Thanks in advance :)
import React, { useState } from "react";
import { Dropdown } from "semantic-ui-react";
const options = [
{ key: "English", text: "English", value: "English" },
{ key: "French", text: "French", value: "French" },
{ key: "Spanish", text: "Spanish", value: "Spanish" },
{ key: "German", text: "German", value: "German" },
{ key: "Chinese", text: "Chinese", value: "Chinese" }
];
const DropDownWithHooks = () => {
const [dropDownOptions, setDropDownOptions] = useState(options);
const [currentValue, setCurrentValue] = useState("");
const handleAddition = (e, { value }) => {
setDropDownOptions((prevOptions) => [
{ text: value, value },
...prevOptions
]);
};
const handleChange = (e, { value }) => setCurrentValue(value);
return (
<Dropdown
options={dropDownOptions}
placeholder="Choose Language"
search
selection
fluid
allowAdditions
value={currentValue}
onAddItem={handleAddition}
onChange={handleChange}
/>
);
};
export default DropDownWithHooks;
Working Sandbox

How to convert function component to class component in fluent UI?

I am creating multi select drop down in Office fabrics.I saw the code.It contain the functional component.I want to change in class component.and How can we store the selected options in state variable?
please guide me.I am new in spfx share-point.
Code given below:-
import * as React from 'react';
import { Dropdown, DropdownMenuItemType, IDropdownOption, IDropdownStyles } from 'office-ui-fabric-react/lib/Dropdown';
const dropdownStyles: Partial<IDropdownStyles> = { dropdown: { width: 300 } };
const DropdownControlledMultiExampleOptions = [
{ key: 'fruitsHeader', text: 'Fruits', itemType: DropdownMenuItemType.Header },
{ key: 'apple', text: 'Apple' },
{ key: 'banana', text: 'Banana' },
{ key: 'orange', text: 'Orange', disabled: true },
{ key: 'grape', text: 'Grape' },
{ key: 'divider_1', text: '-', itemType: DropdownMenuItemType.Divider },
{ key: 'vegetablesHeader', text: 'Vegetables', itemType: DropdownMenuItemType.Header },
{ key: 'broccoli', text: 'Broccoli' },
{ key: 'carrot', text: 'Carrot' },
{ key: 'lettuce', text: 'Lettuce' },
];
export const DropdownControlledMultiExample: React.FunctionComponent = () => {
const [selectedKeys, setSelectedKeys] = React.useState<string[]>([]);
const onChange = (event: React.FormEvent<HTMLDivElement>, item: IDropdownOption): void => {
if (item) {
setSelectedKeys(
item.selected ? [...selectedKeys, item.key as string] : selectedKeys.filter(key => key !== item.key),
);
}
};
return (
<Dropdown
placeholder="Select options"
label="Multi-select controlled example"
selectedKeys={selectedKeys}
onChange={onChange}
multiSelect
options={DropdownControlledMultiExampleOptions}
styles={dropdownStyles}
/>
);
};
You can do the following:
export class DropdownControlledMultiExample extends React.Component {
state = {
selectedKeys: []
}
onChange = (event: React.FormEvent<HTMLDivElement>, item: IDropdownOption): void => {
if (item) {
this.setState({
selectedKeys:
item.selected
? [...this.state.selectedKeys, item.key as string]
: this.state.selectedKeys.filter(key => key !== item.key),
});
}
};
render() {
return (
<Dropdown
placeholder="Select options"
label="Multi-select controlled example"
selectedKeys={this.state.selectedKeys}
onChange={this.onChange}
multiSelect
options={DropdownControlledMultiExampleOptions}
styles={dropdownStyles}
/>
);
}
};

Select form field not populating with options from state in ReactJS

This is my select function
import React from "react";
const Select = ({ name, label, options, error, ...rest }) => {
return (
<div className="form-group">
<label htmlFor={name}>{label}</label>
<select {...rest} id={name} name={name} className="form-control">
<option value="" />
{options.map((option) => (
<option key={option.id} value={option.id}>
{option.name}
</option>
))}
</select>
{error && <div className="alert alert-danger">{error}</div>}
</div>
);
};
export default Select;
This is the component state
state = {
data: {
vat: "",
city: "",
country: "",
mobile_number: "",
address: "",
has_conference: false,
star_rating: "",
},
errors: {},
hotel_type: [],
};
This function to populate data in the hotel_type
populateHotel_Types = () => {
let hotel_type = [...this.state.hotel_type];
hotel_type = [
{ id: "hotel", value: "hotel", name: "Hotel" },
{ id: "apartment", value: "apartment", name: "Apartment" },
{ id: "villa", value: "villa", name: "Villa" },
];
this.setState({ hotel_type });
};
And Finally this is the render function
{this.renderSelect(
"hotel_type",
"Hotel Type",
this.state.hotel_type
)}
Render select function
renderSelect(name, label, options) {
const { data, errors } = this.state;
return (
<Select
options={options}
name={name}
value={data[name]}
label={label}
onChange={this.handleChange}
error={errors[name]}
/>
);
}
Now i am struggling to get the data populated in the renderselect function. I am quite new to react and i am actually assuming this might be a silly question therefore kindly bear with me. What could be wrong with this code. Please help. Thanks
I think in first place, you have a problem here:
populateHotel_Types = () => {
let hotel_type = [...this.state.hotel_type];
hotel_type = [
{ id: "hotel", value: "hotel", name: "Hotel" },
{ id: "apartment", value: "apartment", name: "Apartment" },
{ id: "villa", value: "villa", name: "Villa" },
];
this.setState({ hotel_type });
};
Here, you are filling hotel_type with your state. And below, you are redefining the array, so you will have just this 3 new objects. So should do this to have the full list:
populateHotel_Types = () => {
const hotel_type = [
...this.state.hotel_type,
{ id: "hotel", value: "hotel", name: "Hotel" },
{ id: "apartment", value: "apartment", name: "Apartment" },
{ id: "villa", value: "villa", name: "Villa" },
];
this.setState({ hotel_type });
};
I suspected this was a silly question and indeed it was. I was forgetting to run the function populateHotel_Types in the componentDidMount function. Therefore the state was not being updated appropriately. I am leaving this here so that any newbie like myself will get an answer to such a scenario

Resources