import huge option list into main component - reactjs

I'm using React 16.12, and I have a component that contains a select dropdown box for a form. The option field section is huge...like over 75 choices. With it being so long, I don't want to clutter up my main form component.
So I tried putting it in a separate file called options.js like this:
<option selected>Open this select menu</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
But whenever I try to import, I just get this error:
Failed to compile
Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment
<>...</>?
I want it do look something like this in the main form component:
import React from "react";
import "./options" As OptionListing;
const App = () => (
<Form>
<select name="optionTypes">
<OptionListing>
</select>
</Form>
);
render(<App />, document.getElementById("root"));
Is this possible?
Thanks!

This is possible but you need one encapsulating component, try this.
import React from "react";
const OptionList = () => {
return (
<React.Fragment>
<option selected>Open this select menu</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</React.Fragment>
)
}
export default OptionList
This is an alternate way of doing the same thing in shorthand (newer React versions)
import React from "react";
const OptionList = () => {
return (
<>
<option selected>Open this select menu</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</>
)
}
export default OptionList
https://reactjs.org/docs/fragments.html

try modifying Options.js like below
<React.Fragment>
<option selected>Open this select menu</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</React.Fragment>
OR return array of elements like
const options = [
<option selected>Open this select menu</option>,
<option value="1">One</option>,
<option value="2">Two</option>,
<option value="3">Three</option>,
];
and use as
<Form>
<select name="optionTypes">
{options}
</select>

You can create a reusable Select component like this:
export default function Select({ name, options, handleSelected }) {
return (
<select name={name} onChange={e => handleSelected(e.target.value)}>
{options.map(({ key, title }) => (
<option key={key} value={key}>
{title}
</option>
))}
</select>
);
}
App.js
import React from "react";
import Select from "./Select";
const options = [
{
key: 1,
title: "Option 1"
},
{
key: 2,
title: "Option 2"
},
{
key: 3,
title: "Option 3"
}
];
export default function App() {
const onSelected = option => {
console.log(option);
};
return (
<div>
<form>
<Select
name="optionTypes"
options={options}
handleSelected={onSelected}
/>
</form>
</div>
);
}
You can also put the options to a file, and import it to the App.js.
For example:
options.json
[
{
"key": 1,
"title": "Option 1"
},
{
"key": 2,
"title": "Option 2"
},
{
"key": 3,
"title": "Option 3"
}
]
App.js
import React from "react";
import Select from "./Select";
import options from './options.json';
export default function App() {
const onSelected = option => {
console.log(option);
};
return (
<div>
<form>
<Select
name="optionTypes"
options={options}
handleSelected={onSelected}
/>
</form>
</div>
);
}
Codesandbox
If your options fields keys are different from key and title, before passing the options, you may use Array.map() to transform.

Related

Search only with text ignoring emoji in antd Select component

I have select component of antd where option label is not text. Option label has text along with emoji. Now If user want to search for particular text, the select component is not able to search the text which has emojis.
What I want to have is User should search a particular text ignoring the emoji.
import React from 'react';
import 'antd/dist/antd.css';
import './index.css';
import { Select } from 'antd';
const { Option } = Select;
const App = () => (
<Select
showSearch
style={{
width: 200,
}}
placeholder="Search to Select"
optionFilterProp="children"
filterOption={(input, option) => option.children.includes(input)}
>
<Option value="1"><span>😁</span> Not Identified</Option>
<Option value="2"><span>🙄</span> Closed</Option>
<Option value="3"><span>😪</span> Communicated</Option>
<Option value="4"><span>😚</span> Identified</Option>
<Option value="5"><span>🥱</span> Resolved</Option>
<Option value="6"><span>😫</span> Cancelled</Option>
</Select>
);
export default App;
If need, I have a codesandbox link.
here just use toLowerCase() string function it's work i just updated pls check here codesandbox link
import React from "react";
import "antd/dist/antd.css";
import "./index.css";
import { Select } from "antd";
const { Option } = Select;
const onHandleSearch = (input, option) => {
let optionChildren = option.children.filter(
(item) => typeof item === "string"
);
return optionChildren[0].toLowerCase().includes(input.toLowerCase());
};
const App = () => (
<Select
showSearch
style={{
width: 200
}}
placeholder="Search to Select"
optionFilterProp="children"
filterOption={(input, option) => onHandleSearch(input, option)}
>
<Option value="1">
<span>😁</span> Not Identified
</Option>
<Option value="2">
<span>🙄</span> Closed
</Option>
<Option value="3">
<span>😪</span> Communicated
</Option>
<Option value="4">
<span>😚</span> Identified
</Option>
<Option value="5">
<span>🥱</span> Resolved
</Option>
<Option value="6">
<span>😫</span> Cancelled
</Option>
</Select>
);
export default App;

How to get the value of custom atttributes in react hooks?

How do I get the value of custom attributes using react hooks?
Here is sample code in code sandbox : demo live
code
import "./styles.css";
import React, { useState } from "react";
export default function App() {
const [value, setValue] = useState("");
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<select
onChange={(e) => {
console.log("value", e.target.value);
console.log("description", e.target.description);
setValue(e.target.value);
}}
name="cars"
id="cars"
>
<option value="volvo" description="hahahahaa">
Volvo
</option>
<option value="saab" description="hehehehehe">
Saab
</option>
<option value="opel" description="hoooooooo">
Opel
</option>
<option value="audi" description="huuuuuuuuuu">
Audi
</option>
</select>
</div>
);
}
I am able to get the value of attribute value but not the custom description.
I get undefined console.log("description", e.target.description);
What is wrong here?
e.target give you the select tag, you can get the option tag and the description like this:
console.log("description", e.target.childNodes[e.target.selectedIndex].getAttribute("description"));
In your example target is the <select> and you would need to traverse to the selected option and get the attribute value.
It really doesn't seem practical to store data in a custom option attribute when you could use a hashmap with values as keys
const Example = () => {
const [desc, setDesc] = React.useState('')
const descriptions = {
volvo:'hahahahaa',
saab:'hehehehehe',
opel:'hoooooooo'
}
const handleChange = (e)=>{
const val = e.target.value,
des = descriptions[val]
console.clear()
console.log("value",val);
console.log("description", des);
setDesc(des)
}
return (
<div>
<div>Description: {desc}</div>
<select
onChange={handleChange}
name="cars"
id="cars"
>
<option value="volvo">
Volvo
</option>
<option value="saab">
Saab
</option>
<option value="opel" >
Opel
</option>
</select>
</div>
);
};
// Render it
ReactDOM.render(
<Example title="Example using Hooks:" />,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>

React - Ant Design Form-Item name props broke Select value

I m using antD and if I use select component inside of form item and if this form item has name as props I can not set value to my select component while page was rendering.
Just make it clear what I tried to say, I prepared a example and you can copy and paste it to the codesandbox or etc.
import React from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Form, Input, Button, Select } from 'antd';
const { Option } = Select;
export const Demo =()=> {
let formRef = React.createRef();
return (
<Form ref={formRef} name="control-ref">
<Form.Item
label="Gender"
rules={[
{
required: true,
},
]}
>
<Select value="male">
<Option value="male">male</Option>
<Option value="female">female</Option>
<Option value="other">other</Option>
</Select>
</Form.Item>
</Form>
);
}
ReactDOM.render(<Demo />, document.getElementById('container'));
If you try to give name props to form item in this example your select component's initial value will not
be set.
More over using hooks not solved my problem.
I do not fully understand your question, but as far as I do, I'll try to help.
You can try useRef.
import React,{useRef, useEffect} from 'react';
export const Demo =()=> {
var formRef = useRef();
useEffect(() => {
formRef.current.setFieldsValue({
select:"male"
})
});
<Form ref={formRef} name="control-ref">
<Form.Item
label="Gender"
name="select"
rules={[
{
required: true,
},
]}
>
<Select>
<Option value="male">male</Option>
<Option value="female">female</Option>
<Option value="other">other</Option>
</Select>
</Form.Item>
</Form>
);}
Do not forget to give the name of the relevant Form.Item.

How to use Multi-Select Dropdown in react-bootstrap

I am using react-bootstrap library. This library having a module called DropdownButton. So i am able to display data in dropdown. This is single selection data.
<DropdownButton
bsStyle="success"
title={this.state.addLeadStageSelectTitle}
key={"addleadstageDropDown"}
id={"addleadstageIDAdd"}
onSelect={this.handleSelectLeadStageAdd}
>
{this.state.vtx_sales_lead_status.map(objs => {
return (
<MenuItem eventKey={objs.id}>{objs.name}</MenuItem>
)
}
)}
</DropdownButton>
But I am trying to create it multiselect with same library.
Here is a multi-select example using hooks and react-bootstrap.
import React, { useState } from "react";
import { Col, Form } from "react-bootstrap";
export default function App() {
const [field, setField] = useState([]);
return (
<Form.Group as={Col} controlId="my_multiselect_field">
<Form.Label>My multiselect</Form.Label>
<Form.Control as="select" multiple value={field} onChange={e => setField([].slice.call(e.target.selectedOptions).map(item => item.value))}>
<option value="field1">Field 1</option>
<option value="field2">Field 2</option>
<option value="field3">Field 3</option>
</Form.Control>
</Form.Group>
);
}
I've checked the react-bootstrap documentation and it looks like there isn't a multiselect functionality.
So you can use a third party library, like: react-bootstrap-multiselect.
It's a Multiselect component for React (with Bootstrap). This is a React wrapper around an existing jQuery / Bootstrap library: bootstrap-multiselect
Basic usage:
import Multiselect from 'react-bootstrap-multiselect'
const data = [{ value:'One', selected:true }, { value: 'Two' }, { value:'Three' }]
const App = props => {
return <Multiselect onChange={props.handleChange} data={data} multiple />
}
Demo.
It is supported now:
import { Form } from 'react-bootstrap';
// [...]
<Form>
<Form.Control as="select" multiple value={options} onChange={onSelectedOptionsChange}>
{options.map(options => (
<option key={option.name} value={option.value}>
{option.name}
</option>
))}
</Form.Control>
</Form>

option disabled selected not set as default value in React js dropdown

In the dropdown below, why is Select City not appearing in the dropdown as the default selection on page load ? Instead, City1 appears as the default selected option.
I have the options for default coded as :
<option value="" disabled selected>
Select City
</option>
The options are coded in another js file as below:
import React from 'react'
const cityoptions = [
{ value: '1', name: 'City1' },
{ value: '2', name: 'City2' },
{ value: '3', name: 'City3' },
....
The following is the component for dropdown.
import React from 'react'
import PropTypes from 'prop-types'
import Select from '../others/input/select'
import cityOptions from './city-options'
const InputCities = ({ value, change }) => (
<div className="edit_caste_div">
<Select
placeholder="Select option"
value={value}
valueChange={e => change('city', e)}
className="edit_city my2"
>
<option value="" disabled selected>
Select City
</option>
{cityOptions.map((e, key) => {
return <option key={key} value={e.value}>{e.name}</option>
})}
</Select>
</div>
)
InputCities.propTypes = {
value: PropTypes.string.isRequired,
change: PropTypes.func.isRequired,
}
You should add a defaultValue attribute to select and set it to the disabled value
<Select
defaultValue="Select City"
valueChange={e => change('city', e)}
className="edit_city my2"
>
<option value="Select City" disabled>
Select City
</option>
{cityOptions.map((e, key) => {
return <option key={key} value={e.value}>{e.name}</option>
})}
</Select>

Resources