0

How to convert this class based component into functional component.AS this is a simple class based component in react,I want to convert this react class based component into functional component with redux hooks.I want to use redux hoooks in this component.I am not comfortable with class based components as this keyword is most confusing word for me .I want to use useSelector hook and useDispatch from react-redux hook.In this component in my am using conditional rendering

import React from "react";
import { connect } from "react-redux";  
import { AUTH_ERRORS, login } from "../ducks/client";
class Login extends React.Component {
  render() {
    if (this.props.error === AUTH_ERRORS.CERTIFICATE) {
      return (
        <div className="Page">
          <h2>Connection error</h2>
        </div>
      );
    }
   
    return (
      <div className="Home Page">
        <h2>Login</h2>
        <form className="form" onSubmit={this.handleSubmit}>
          {this.props.error === AUTH_ERRORS.CREDENTIALS && (
            <h4 className="formError">Incorrect username or password</h4>
          )}
   
          <label htmlFor="jid">Username</label>
          <input
            ref={(el) => (this._jid = el)}
            type="text"
            name="jid"
            id="jid"
            placeholder="Username"
          />
          <label htmlFor="password">Password</label>
          <input
            ref={(el) => (this._password = el)}
            name="password"
            type="password"
            id="password"
            placeholder="Password"
          />
          <div className="actions">
            <input type="submit" value="Log in" />
          </div>
        </form>
      </div>
    );
  }
   
  handleSubmit = (e) => {
    e.preventDefault();
    if (this._jid.value.length && this._password.value.length) {
      this.props.login(this._jid.value, this._password.value);
    }
  };
}
   
const mapStateToProps = (state) => ({
  error: state.client.error,
});
   
export default connect(mapStateToProps, { login })(Login);
  • 1
    Does this answer your question? [Convert class component to functional component in React](https://stackoverflow.com/questions/66393346/convert-class-component-to-functional-component-in-react) – Bilal Hussain Sep 17 '21 at 15:16

1 Answers1

0

Here is your code as a functional component:

const { Provider, useDispatch, useSelector } = ReactRedux;
const { createStore, applyMiddleware, compose } = Redux;

const initialState = {
  client: { error: {} },
};
//action creators
const loginAction = (id, pwd) => ({
  type: 'LOGIN',
  payload: { id, pwd },
});
const reducer = (state, { type, payload }) => {
  console.log('in reducer', type, payload);
  return state;
};
//creating store with redux dev tools
const composeEnhancers =
  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
  reducer,
  initialState,
  composeEnhancers(
    applyMiddleware(
      () => (next) => (action) => next(action)
    )
  )
);
const AUTH_ERRORS = {};
function Login(props) {
  const dispatch = useDispatch();
  const _jid = React.useRef();
  const _password = React.useRef();
  const login = React.useCallback(
    (id, pwd) => dispatch(loginAction(id, pwd)),
    [dispatch]
  );
  const handleSubmit = React.useCallback(
    (e) => {
      e.preventDefault();
      if (
        _jid.current.value.length &&
        _password.current.value.length
      ) {
        login(_jid.current.value, _password.current.value);
      }
    },
    [login]
  );
  const error = useSelector((state) => state.client.error);

  if (error === AUTH_ERRORS.CERTIFICATE) {
    return (
      <div className="Page">
        <h2>Connection error</h2>
      </div>
    );
  }

  return (
    <div className="Home Page">
      <h2>Login</h2>
      <form className="form" onSubmit={handleSubmit}>
        {error === AUTH_ERRORS.CREDENTIALS && (
          <h4 className="formError">
            Incorrect username or password
          </h4>
        )}

        <label htmlFor="jid">Username</label>
        <input
          ref={_jid}
          type="text"
          name="jid"
          id="jid"
          placeholder="Username"
        />
        <label htmlFor="password">Password</label>
        <input
          ref={_password}
          name="password"
          type="password"
          id="password"
          placeholder="Password"
        />
        <div className="actions">
          <input type="submit" value="Log in" />
        </div>
      </form>
    </div>
  );
}

ReactDOM.render(
  <Provider store={store}>
    <Login />
  </Provider>,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/7.2.0/react-redux.min.js"></script>


<div id="root"></div>

Here is the answer to your other question

const Members = ['John', 'Ali', 'Nagar', 'colony'];
const asName = (names) =>
  names.length === 0
    ? 'no members'
    : names.length === 1
    ? `${names[0]}`
    : names.length === 2
    ? `${names[0]},${names[1]}`
    : `${names[0]},${names[1]} +${names.length - 2}`;

console.log(asName(Members.slice(0, 0)));
console.log(asName(Members.slice(0, 1)));
console.log(asName(Members.slice(0, 2)));
console.log(asName(Members.slice(0, 3)));
console.log(asName(Members.slice(0, 4)));
HMR
  • 37,593
  • 24
  • 91
  • 160