Charl
Charl

Reputation: 155

Converting functional component to class based component

I need to convert a functional component to a class based component. I am fairly new to React but I have tried to convert the component. I get the error - ReferenceError: Cant find variable: Props

My question is, where do I add props which was present in the class based component to make the conversion work ?

The class based component which is a modal with a form triggered from a parent component,this works well. The form uses state variables which dont work in a class based component so I need to convert the current functional component to a class based component. I'm using version 16.6.3 of React because other packages do not work with newer versions of React-Native so I cant use hooks with this version.

Functional component

const ShowModal = props => (
  <Modal
    visible={props.display}
    animationType="slide"
    onRequestClose={() => console.log("closed")}
  >
   ...Other stuff in here. 
 </Modal>
);
export default ShowModal;

Class based component

export default class ShowModal extends Component {
  state = {     
  };

  render() {
    return (
      ...Other stuff in here 
    );
  }
}

I get the error - ReferenceError: Cant find variable: Props

Upvotes: 0

Views: 118

Answers (2)

Wijitha
Wijitha

Reputation: 1389

I presume you want to use State, as the reason for moving to a Class component. Instead I suggest to use React Hooks which is the newest and elegant approach.

const ShowModal = props => (

const [state, setState] = React.useState({});

  <Modal
    visible={props.display}
    animationType="slide"
    onRequestClose={() => console.log("closed")}
  >
   ...Other stuff in here. 
 </Modal>
);

React Hooks: https://medium.com/frontmen/react-hooks-why-and-how-e4d2a5f0347

Upvotes: 0

Dupocas
Dupocas

Reputation: 21297

In class based components props is exposed in the main scope of the class. You should read it using this keyword

class Component extends React.Component{
    render(){return this.props.value}
}

Upvotes: 3

Related Questions