'Change Value From Another Component
Hi guys I started learning React recently and I am stuck here with this problem. Where i use this TagsInput component I made a button that needs to reset the searchValue of the TagsInput component.
By that I meant this:
const [searchValue, setSearchValue] = useState('')
from the TagsInput component.
This is the entire TagsInput component:
import React, {useState} from 'react';
import '../styles/InputField.scss'
import {useDebounce} from "react-use";
import {autocompleteCall} from "../../helpers/helpers";
const TagsInput = ({url, placeholder, tags, setTags, name, setIsEdited, className}) => {
const [resultTags, setResultTags] = useState([])
const [searchValue, setSearchValue] = useState('')
const [isReady, cancel] = useDebounce(
async () => {
const res = await autocompleteCall(url, searchValue)
setResultTags(res)
},
400,
[searchValue]
);
//remove item from array
const removeTag = (index) => {
const filteredTags = tags.filter((item, i) => {
return i !== index
})
setTags(filteredTags)
setIsEdited(true)
}
//add tag in array
const addTag = (item) => {
if (!tags.some(tag => tag.id === item.id)) {
setTags([...tags, item]);
}
}
const handleChange = (e) => {
setSearchValue(e.target.value)
setIsEdited(true)
}
return (
<>
<div className={"tags-input " + className}>
{
(tags || []).map((tag, i) => {
return <span key={i} className="tag ">{tag.name}
<span onClick={() => removeTag(i)}
className={'ml-2 pointer'}>× </span>
</span>
})
}
<input name={name} type="text" onChange={handleChange} placeholder={placeholder}
size="1"/>
</div>
{resultTags && <div className={'d-flex flex-wrap mt-1'}>{(resultTags || []).map((item, i) => {
return <span className={'res-tag pointer'} key={i} onClick={() => addTag(item)}>{item.name}</span>
})}</div>}
</>
);
};
export default TagsInput;
and I use it here:
import React, { useState, useEffect } from "react";
import TagsInput from "../../../App/components/TagsInput";
// other imports
<TagsInput
placeholder={"Type your skills"}
url={"/api/info/skills/"}
tags={tags}
setTags={setTags}
name={"skills"}
setIsEdited={setIsEdited}
/>
<button onClick={()=>{
// reset the TagsInput Value to be ''
// setSearchValue('') // Something like this. This doesn't work of course
}} ></button>
I don't even know how to approach this problem. Is it doable? Any help would be much appreciated!
Solution 1:[1]
You can send the setSearchValue through the props and use it in the parent component
Check this resources
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Indana Rishi |
