Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overcoming lack of refs in stateless components

Tags:

reactjs

I'd like to create a stateless Search component. When the button is clicked, I need to access the value of the search field. Is the following an acceptable way to do this? Are they any drawbacks to this approach?

const Search = ({onBtnClick}) => {
    const onClick = (e) => {
      const query = e.target.previousSibling.value;
      onBtnClick(query);
    };  

    return(
      <div>
        <input type="search" />
        <button onClick={onClick}>Search</button>
      </div>
    )   
  }
like image 623
user5325596 Avatar asked Feb 03 '26 13:02

user5325596


1 Answers

In stateless components you can use ref with function, like so

const Search = ({ onBtnClick }) => {
  let search;
  
  const setNode = (node) => {
    search = node;
  };
  
  const onClick = () => {
    onBtnClick(search.value);
  };  

  return (
    <div>
      <input type="search" ref={ setNode } />
      <button onClick={ onClick }>Search</button>
    </div>
  );  
}

function onBtnClick(value) {
  console.log(value);
}

ReactDOM.render(
  <Search onBtnClick={onBtnClick} />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>
like image 137
Oleksandr T. Avatar answered Feb 05 '26 05:02

Oleksandr T.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!