iamafasha
iamafasha

Reputation: 794

Track the value or event change of children prop in react

So I have a component that I use in this way.

<SBCAInput>
  <input  defaultValue="" type="email" />
</SBCAInput>

And I implemented in the SBCAInput component like this.

import React , {useState} from 'react'

function SBCAInput(props) {
    const [value, setValue] = useState("");
    return (
        <div className={`sbca-input mb-3 ${ value==="" ? "" : "input-not-empty"}`}>
            <label>Email address</label>
            {props.children}
        </div>
    )
}

export default SBCAInput

Now the challenge is I want to be able to detect if the value of the input is empty and change classes on the div container in the SBCAInput component.

How do I track the value of the input component?

Upvotes: 1

Views: 438

Answers (1)

Ajeet Shah
Ajeet Shah

Reputation: 19863

You can access value using children.props.value:

Parent component:

const [email, setEmail] = useState('')

function handleChange(e) {
  setEmail(e.target.value)
}

<SBCAInput>
  <input type="email" value={email} onChange={handleChange}/>
</SBCAInput>

SBCAInput component:

function SBCAInput({ children }) {
  return (
    <div
      className={`sbca-input mb-3 ${
        children.props.value ? 'input-not-empty' : ''
      }`}
    >
      <label>Email address</label>
      {children}
    </div>
  )
}

Upvotes: 1

Related Questions