Search code examples
javascriptreactjsreact-hooksreact-functional-componentreact-class-based-component

Can I change class component into functional component? - Reactjs


I use class component. Just testing it. Now I don't know how to convert it into functional. This is my code:

class PostList extends Component {
   constructor(props) {
    super(props);
    this.state = {
      info: []
    };
  }

  componentDidMount() {
    axios
      .get("https://api2.binance.com/api/v3/ticker/24hr")
      .then((response) => {
        this.setState({
          info: response.data
        });
        console.log(response.data);
      });
  }

  render() {
    const { info } = this.state;
    return (
      <div>
        <h2>post!</h2>
        {info.map((user) => (
          <div key={user.symbol}>
            <h6>{user.priceChange}</h6>
          </div>
        ))}
      </div>
    );
  }
}

export default PostList;

I should use this code in my redux and I need to convert it into functional component

I want something like this:

export const PostList = () =>{
   return (
    //my code using axios,       
   )
}```



 

Solution

  • For functional component, you should use hooks instead of classify components default state and componentDidMount. So for define a new state you need to use useState and for componentDidMount you need to use useEffect:

    const PostList  = (props) => {
       const [state,setState] = useState({info:[]});
       useEffect(()=>{
          axios
          .get("https://api2.binance.com/api/v3/ticker/24hr")
          .then((response) => {
            setState({
              info: response.data
            });
            console.log(response.data);
          });
         },[])
    
      const { info } = state;
        return (
          <div>
            <h2>post!</h2>
            {info.map((user) => (
              <div key={user.symbol}>
                <h6>{user.priceChange}</h6>
              </div>
            ))}
          </div>
        );
    }
    
    
    export default PostList;