Home > Software design >  Get <p> value using React ref
Get <p> value using React ref

Time:12-01

Is there some way to get this "name" value after clicking on li item and set it to selectedBranch state using ref?

  const [selectedBranch, setSelectedBranch] = useState(null);
  const selectRef = useRef();

  const selectDeliveryBranch = () => {};

  return (
    <li
      onClick={selectDeliveryBranch}
    >
      <p ref={selectRef}>{props.name}</p>
    </li>

CodePudding user response:

You do not want to use ref to do this, instead simply create a callback:

return <li onClick={()=>setSelectedBranch(props.name)}>
    <p>props.name</p>
</li>

No ref needed

CodePudding user response:

are you sure you need to use the ref ? Why can't you do that ?

const [selectedBranch, setSelectedBranch] = useState(null);
const selectRef = useRef();

return (
    <li
        onClick={() => setSelectedBranch(props.name)}
    >
        <p ref={selectRef}>{props.name}</p>
    </li>
  • Related