Search code examples
react-nativereact-propses6-class

How do I get the props in this ES6 Class?


I tried using constructor (props) but still getting cant find variable: props Hot do I get the props in this:

    export default class DetailScreen extends React.Component {
  state = {
    value: '399',
    checked: 'Pan Crust',
  };

  render() {
    const productId = props.navigation.getParam('productId');
    constselectedProduct = useSelector((state) =>
      this.state.products.vegProducts.find((prod) => prod.id === productId),
    );

    const {checked} = this.state;

Solution

  • props are accessed with this in class components.

    So, the first line in the render function should be

    const productId = this.props.navigation.getParam('productId');
    

    Update For react navigation 5.x

    You should be able to access route params like this

    const productId = this.props.route.params.productId;
    

    Hooks should be used in functional components. You should refactor your code to look like this instead

    
    export const DetailScreen = ({route)} => {
    const [value, setValue] = useState('399');
    const [checked, setChecked] = useState('Pan Crust');
    const productId = route.params.productId;
    
    return (
       // return view here
     )
    }