I have a parent form component and a child component which I'm using for auto-completing text input. I'm passing an array of objects called autoCompTxt that has a name and id field, from the Parent component to the Child component.
//Parent:
const [obj, setObj] = useState([{name:'',id:''}]);
<AutoCompleteText onChange={text => setName(text)} autoCompTxt={obj} name="sampleName" id="sampleId" />
In the child component I'm trying to filter on the name string, using 'v.name'. But the suggestions array gets populated with Objects instead of Strings.
//Child:
let suggestions = [];
suggestions = props.autoCompTxt.sort().filter(v => regex.test(v.name));
console.log(suggestions);
AutoCompleteText.js:22 Suggestions: [object Object],[object Object]
I've tried using JSON.stringify() and ${v.name}. But they haven't helped.
The issue is that the line below is returning 2 objects. {name:"name1", id:1},{name:"name2", id:2}
instead of returning just the names. "name1","name2"
suggestions = props.autoCompTxt.sort().filter(v => regex.test(v.name));
import React from 'react';
import { useState } from 'react';
import { Input } from 'reactstrap';
const AutoCompleteText = props => {
const [suggestions, setSuggestions] = useState([]);
const [text, setText] = useState('');
const onTextChanged = (e) => {
const value = e.target.value;
let suggestions = [];
if (value.length > 0) {
setSuggestions([]);
const regex = new RegExp(`^${value}`, 'i');
console.table(props);
suggestions = props.autoCompTxt.sort().filter(v => regex.test(v.name));
console.log('Suggestions: ' + suggestions);
}
setSuggestions(suggestions);
setText(value);
}
function suggestionSelected(value) {
setSuggestions([]);
props.onChange(value);
setText(value);
}
function renderSuggestions() {
if (suggestions.length === 0) {
console.log(suggestions);
return null;
}
return (
<ul>
{suggestions.map((item) => <li onClick={() => suggestionSelected(item)}>{item}</li>)}
</ul>
)
}
return (
<div>
<Input value={text} onChange={onTextChanged} type="text" />
{renderSuggestions()}
</div>
)
};
export default AutoCompleteText;