Search code examples
reactjstypescriptclassuse-state

Share info from class component in to function component with useState


//parent
const [mailArray, setMailArray] = useState([]);

 return (
          <StyledInputBox>
            <Chips setMailArray={setMailArray} />  //does not work
          </StyledInputBox>
          )
          
//children <<Chips>>
export default class Chips extends React.Component {
  state = {
    items: [''],
    value: '',
    error: null,
  };
}          

class component <> is children of function component. I want to get info from children's state into a parent with props and useState.


Solution

  • You should change your mailArray in your parent and pass it to your child component. Or if you want to change your mailArray in your child component you should pass a function to your Chips component that give a parameter that it trigger when for example you click on an element in your Chips component like below:

    const changeMail = (value) => {
    setMailArray(value)
    }
     return (
              <StyledInputBox>
                <Chips onChange={changeMail} />  //does not work
              </StyledInputBox>
              )
    
    

    and in your Chips component should be for example some code like below:

    render() {
    return (<div onClick={this.props.onChange('some value')}>chips component</div>)
    }