Home > front end >  Converting stateful to stateless component
Converting stateful to stateless component

Time:09-29

I have this working stateful component in React:

import React, {Component}  from "react";

class MyComponent extends Component {
  constructor() {
    super();
    this.myRef = React.createRef();
    this.state = {
            array: [],
            noresults: false
        };
  }
  
  loadData = () => {
    let data = this.myRef.current.value;
    let url = "someurl=" data;
    if(!data) {
      return;
    }
        fetch(url)
            .then((res) => res.json())
            .then((json) => {
                if(json.data.length > 0) {
                  this.setState({
                      array: json.data,
                      noresults: false
                  });
                } else {
                  this.setState({
                      noresults: true
                  });
                }
                
            })
    }
render() {
  const { array, noresults } = this.state;
  return (
    <div>
      <section>
        <input ref={this.myRef} type="number"/>
        <button onClick={this.loadData}>Click Here</button>
      </section>

    
    <ul>
        
        {
                array.map((e) => ( 
                <li key = { e.key } >
                    { e.data }
                    </li>
                ))
            }
      </ul>

      {noresults && <div>No Records</div>}
    </div>
  );
}
}

export default MyComponent

I want to convert this to stateless like this:

function MyComponent() {

  return (
    <div>
      <section>
        <input type="number"/>
        <button>Click Here</button>
      </section>

      <ul>
        <li></li>
      </ul>

      <div>No Records</div>
    </div>
  );
}

export default MyComponent

Now how can I pass data of input to my method to make API call. Also how to pass the response from API to display as ul and li elements?

CodePudding user response:

Just pass it as component props:

const MyComponent = ({array = [], loadData = () => {}}) => {
  const [inputValue, setInputValue] = useState();
  
  const handleInputChange = (evt) => {
    setInputValue(evt.target.value);
  };

  return (
    <div>
      <section>
        <input type="number" onChange={handleInputChange} />
        <button onClick={e => loadData(e, inputValue)}>Click Here</button>
      </section>

      <ul>
          {array.map((e) => (<li key={e.key}>{e.data}</li>))}
      </ul>

      {array.length === 0 && <div>No Records</div>}
    </div>
  );
}

For input, I created a local state which is updated on input change and passed it to loadData function. You can access the current value by parametrizing loadData function:

loadData = (e, currentInputValue) => { ... };
  • Related