Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

naming convention for react hooks and props?

Tags:

reactjs

Component's props names and local state variable names are collide. Is there any naming convention followed globally? See "selected" props and state

function Select({options,selected,onSelect}){

    let [selected,setSelect]=useState(selected)

    //... useeffect to update local state if props changes

    function setSelectLocal(){
       setSelect(e.target.value)
       onSelect(e.target.value)
    }

    return (
    <select onChange={onSelect} value={selected}>
        {options.map((option)=><option>{option}</option>)}
    </select>  
   )
}

Thanks

like image 224
Vimalesan Avatar asked Sep 06 '25 14:09

Vimalesan


1 Answers

I would say const [selectedValue, setSelectedValue] = useState('default value').

However, what might be a better option is let the parent component handle the state and simply pass down the handler via props.

function ParentComponent() {
  const [selectedValue, setSelectedValue] = useState('default value')

  const onChange = (e) => {
    setSelectedValue(e.target.value)
  }

  return (
    <div>
      // other stuff here
      <ChildComponent options={stuff} onChange={onChange} selectedValue={selectedValue} />
    </div>
  )
}

function ChildComponent({ options, onChange, selectedValue }) {
  return (
    <select onChange={onChange} value={selectedValue}>
      {options.map((option)=><option>{option}</option>)}
    </select>  
  )
}
like image 82
Richard Vanbergen Avatar answered Sep 09 '25 23:09

Richard Vanbergen