React Autocomplete - javascript

React_autosuggestion did not show suggestions while typing on input box
even though the same code is copy pasted from documentation react-autosuggestion upi.
<ReactAutocomplete
items={[
{ id: 'foo', label: 'foo' },
{ id: 'bar', label: 'bar' },
{ id: 'baz', label: 'baz' },
]}
shouldItemRender={(item, value) => item.label.toLowerCase().indexOf(value.toLowerCase()) > -1}
getItemValue={item => item.label}
renderItem={(item, highlighted) =>
<div
key={item.id}
style={{ backgroundColor: highlighted ? '#eee' : 'transparent'}} >
{item.label}
</div>
}
value={value}
onChange={e => setCurrentValue( e.target.value )}
onSelect={value => setCurrentValue( value )}
/>
imported as:
import ReactAutocomplete from 'react-autocomplete';
and the value is declared and set using a function:
const [value,setValue]=useState('');
const setCurrentValue=(value)=>{
console.log('hhhh',value)
setValue(value);
}
However, as shown in the screenshot below, the suggestion is not displayed.

Related

React-select multiple selects on one page

I am a bit confused, here is an example with a couple of select inputs that have the same state, please check here: https://stackblitz.com/edit/get-selected-by-value-multi-select-react-agamk4?file=src/App.js so please:
How can I make it so when I select an option the value does not apply to the rest of the select inputs?
How would you put the values in the store for each of the selects?
Do I need multiple stores?
For more clarity, here is a screenshot: https://www.awesomescreenshot.com/image/19798040?key=bb839c650c93b436066e03d33d5515b0 I hope this makes sense? What would be the best approach? Thank you.
I have shared the code in case of only a single state. You can use this method if you want only a single state but having multiple states for different select inputs also won't be bad as you have only 3 inputs. Having single state method would be useful if number of select inputs would have more.
import React, { useState } from 'react';
import Select from 'react-select';
function App() {
const data = [
{
value: 1,
label: 'cerulean',
},
{
value: 2,
label: 'fuchsia rose',
},
{
value: 3,
label: 'true red',
},
{
value: 4,
label: 'aqua sky',
},
{
value: 5,
label: 'tigerlily',
},
{
value: 6,
label: 'blue turquoise',
},
];
// set value for default selection
const [selectedValue, setSelectedValue] = useState([
{ value: [] },
{ value: [] },
{ value: [] },
]);
// handle onChange event of the dropdown
const handleChange = (e, no) => {
setSelectedValue(
selectedValue.map((item) => {
return selectedValue.indexOf(item) === no
? { value: Array.isArray(e) ? e.map((x) => x.value) : [] }
: item;
})
);
};
return (
<div className="App">
<Select
className="dropdown"
placeholder="Select Option"
value={data.filter((obj) => selectedValue[0].value.includes(obj.value))} // set selected values
options={data} // set list of the data
onChange={(event) => handleChange(event, 0)} // assign onChange function
isMulti
isClearable
/>
<br />
<Select
className="dropdown"
placeholder="Select Option"
value={data.filter((obj) => selectedValue[1].value.includes(obj.value))} // set selected values
options={data} // set list of the data
onChange={(event) => handleChange(event, 1)} // assign onChange function
isMulti
isClearable
/>
<br />
<Select
className="dropdown"
placeholder="Select Option"
value={data.filter((obj) => selectedValue[2].value.includes(obj.value))} // set selected values
options={data} // set list of the data
onChange={(event) => handleChange(event, 2)} // assign onChange function
isMulti
isClearable
/>
{selectedValue && (
<div style={{ marginTop: 20, lineHeight: '25px' }}>
<div>
<b>Selected Value: </b> {JSON.stringify(selectedValue, null, 2)}
</div>
</div>
)}
</div>
);
}
export default App;
{selectedValue && (
<div style={{ marginTop: 20, lineHeight: '25px' }}>
<div>
<b>Selected Values: </b>
<span>{
selectedValue.map(item => item.value.length !== 0 ?
<li>{data.filter(data => data.value === item.value[0])[0].label}</li> :
<li>No value selected</li>
)
}</span>
</div>
</div>
)}

after entering the value in the textbox if I hit enter, should see a new chip with the entered value in it

when I click textbox text a menu opens, in that textbox I need to enter some value in the textbox.
after entering the value in the textbox if I hit enter, I should see a new chip with the entered value in it.
so I thought I will create an Onchange event and pass the values to the chip component
but the values are not getting passed.
I think I need to pass values an object to that array.
chipData.push(handleTextBox);
console.log("handleTextBox after push chipData--->", chipData);
can you tell me how to fix it.
providing my code snippet and sandbox below.
https://codesandbox.io/s/material-demo-99sf8
demo.js
const [chipData, setChipData] = React.useState([
{ key: 0, label: "Angular" },
{ key: 1, label: "jQuery" },
{ key: 2, label: "Polymer" },
{ key: 3, label: "React" },
{ key: 4, label: "Vue.js" }
]);
const [hideChip, setHideChip] = React.useState([false]);
const handleClick = event => {
setAnchorEl({ type: "icon", target: event.currentTarget });
};
const handleClickFilter = event => {
setAnchorEl({ type: "textbox", target: event.currentTarget });
};
const handleTextBox = event => {
console.log("handleTextBox event--->", event);
console.log("handleTextBox event.target.value--->", event.target.value);
};
console.log("handleTextBox handleTextBox--->", handleTextBox);
console.log("handleTextBox chipData--->", chipData);
chipData.push(handleTextBox);
console.log("handleTextBox after push chipData--->", chipData);
<Menu
id="simple-menu"
anchorEl={
anchorEl && anchorEl.type === "textbox" && anchorEl.target
}
open={Boolean(anchorEl && anchorEl.type === "textbox")}
onClose={handleClose}
>
<MenuItem>
<form
className={classes.container}
noValidate
autoComplete="off"
>
<TextField
id="standard-name"
label="Name"
className={classes.textField}
onChange={handleTextBox}
// value={values.name}
// onChange={handleChange('name')}
margin="normal"
/>
</form>
</MenuItem>
</Menu>
<Paper className={classes.root}>
{chipData.map(data => {
let icon;
console.log("setHideChip--->", setHideChip);
if (data.label === "React") {
icon = <TagFacesIcon />;
}
return (
<Chip
key={data.key}
icon={icon}
label={data.label}
onDelete={handleDelete(data)}
className={classes.chip}
/>
);
})}
</Paper>
try with this code .
<TextField
fullWidth={true}
id="standard-name"
label="Tags"
className={classes.textField}
onChange={handleChange('tag')}
onKeyDown={(e) => pushToarray(e)}
margin="dense"
/>
on entering you should see tag being added
function pushToarray(e){
if(e.key == 'Enter'){
e.preventDefault();
setValues({ tags : [...values.tags ,e.target.value] ,
tag : ''})
}
}
and normal handleChange of text change in the box :
const handleChange = name => event => {
setValues({ ...values, [name]: event.target.value });
console.log(values)
};
Initialize state like this I have initialized with empty array you can use keys:
const [values, setValues] = React.useState({
tag :'',
tags: [],
})
here is your handleDelete function to remove chips :
function handleDelete(item){
var rm = values.tags.indexOf(item);
values.tags.splice( rm, 1)
setValues( { tags : values.tags})
}
this is how your chip component should be
<Paper className={classes.root}>
{
values.tags && values.tags.map( (tag ,id) =>(
<Chip color="default" className={classes.chip} onDelete={() => handleDelete(tag)} key={id} label={tag}/>
))
}

How to search and find table details using ant design auto complete(react js)

I am using ant design auto complete, vx is my Datasource array(all name list only) and empData is my table datasource .Here my problem is how to search and find the correct details from person name and how to write onSearch function when i select the name and press the search button?
<AutoComplete
dataSource={vx}
placeholder="type"
onChange={this.handleChange
onPressEnter={this.onSearch}
filterOption={(inpvalueutValue, option) => option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1} />
<Button type="primary" onClick={this.onSearch}>Search</Button>
This is my handleChange function
handleChange(value) {
console.log(`selected ${value}`);
}
This is my table
<Table pagination={{ pageSize: 10 }} columns={columns} dataSource={this.state.empData} />
Make this changes to your autocomplete and button tags, The dropdown was auto closing after option select. Try to handle the way you are doing it now. However, search is working fine.
handleSearch = (selectedKeys, confirm) => () => {
confirm();
this.setState({ searchText: selectedKeys[0] });
}
const dataSource1 = ['Amal', 'Chamika', 'Unknown'];
const columns = [{
title: 'Name',
dataIndex: 'name',
key: 'name',
filterDropdown: ({ setSelectedKeys, selectedKeys, confirm}) => (
<div>
<AutoComplete
dataSource={dataSource1}
placeholder="Search name"
value={selectedKeys[0]}
onChange={value => setSelectedKeys(value ? [value] : [])}
/>
<Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>Search</Button>
</div>
),
filterIcon: filtered => <Icon type="smile-o" style={{ color: filtered ? '#108ee9' : '#aaa' }} />,
onFilter: (value, record) => record.name.toLowerCase().includes(value.toLowerCase()),
render: (text) => text,
}, {
title: 'Age',
dataIndex: 'age',
key: 'age',
}, {
title: 'Address',
dataIndex: 'address',
key: 'address',
}];

React render a select field multiple times

I have 5 labels that I need to render and each of them should have a select field with these options: string, fixed, guid, disabled
I implemented the following code
class renderCampaignCodes extends Component {
state = {
defaultCampaigns: [
{ name: 'Campaign Source: utm_source' },
{ name: 'Campaign Medium: utm_medium' },
{ name: 'Campaign Name: utm_campaign' },
{ name: 'Campaign Term: utm_term' },
{ name: 'Campaign Content: utm_content' }
],
defaultTypes: ['string', 'fixed', 'guid', 'disabled']
}
render() {
const { defaultCampaigns } = this.state
return (
<Flexbox flexDirection='column' marginTop='20px' width='600px'>
{
defaultCampaigns.map((campaign, idx) => {
return (
<div key={idx}>
<Flexbox justifyContent='space-between'>
<Flexbox marginTop='40px'>
<label>{campaign.name}</label>
</Flexbox>
<Flexbox>
<Field
name='type'
component={renderSelectField}
label='Type'
children={this.state.defaultTypes.map((item, i) => <MenuItem
key={i}
value={item}
label={item.replace(/^\w/, l => l.toUpperCase())}
primaryText={item.replace(/^\w/, l => l.toUpperCase())}/>)
}
/>
</Flexbox>
</Flexbox>
</div>
)
})
}
</Flexbox>
)
}
}
But the selected value from any of the select fields will show up everywhere:
How can I prevent this from happening?
It looks like the name attribute for each of your selects is being set to the same, causing them all to take the same value from store/state (depending on your implementation).
You will want to namespace the type with something. For example:
<Field
name={`${idx}.type`}
component={renderSelectField}
label='Type'
children={this.state.defaultTypes.map((item, i) => (
<MenuItem
key={i}
value={item}
label={item.replace(/^\w/, l => l.toUpperCase())}
primaryText={item.replace(/^\w/, l => l.toUpperCase())}
/>
))}
/>

ReactJS , How to change form type, from onChange dropdown

I'm learning ReactJS, I have dropdown from semantic-ui , and I want it to add onChange event on it. when dropdown change, the form below also change. is it possible? anyone know how to do it?
this is my code.
layout
class EditForm extends React.Component {
componentWillMount() {
this.setState({
options: [
{ key: 1, text: 'Input', value: '1' },
{ key: 2, text: 'Dropdown', value: '2' },
{ key: 3, text: 'Radio Boxes', value: '3' },
{ key: 4, text: 'Checkboxes', value: '4' },
{ key: 5, text: 'Paragraph', value:'5'},
],
selected: ['0'],
});
}
handleChange = (e, { value }) => this.setState({
value
})
render() {
const { value } = this.state
return(
<Segment clearing>
<Container textAlign='right'>
<Dropdown selection
onChange={this.handleChange}
options={this.state.options}
value={value}
defaultValue={this.state.selected}
/>
</Container>
<Form.Group widths='equal'>
<Form.Field>
<Input
style={{width:'480px'}}
/>
</Form.Field>
<Form.Field >
<Button animated='vertical' floated='right' >
<Button.Content hidden>Delete</Button.Content>
<Button.Content visible>
<Icon name='trash outline' />
</Button.Content>
</Button>
<Button animated='vertical' floated='right'>
<Button.Content hidden>Copy</Button.Content>
<Button.Content visible>
<Icon name='copy' />
</Button.Content>
</Button>
</Form.Field>
</Segment>
);
export default EditForm;
I want it to change depending on selected value. if dropdown is selected. than the dropdown form appear. and so on.
is it possible? what is the best way to do it? Thanks.
You can work with conditional rendering where you check for a specific condition before render your component.
Something as:
render() {
const { value } = this.state
return (
<div>
{value === 'dropdown' && <Component1>...</Component1>}
{value === 'text' && <Component2></Component2>}
{value === 'checkboxes' && <Component3></Component3>}
...
</div>
)
}

Categories

Resources