Sonhja
Sonhja

Reputation: 8448

How can I apply Proptypes properly on my React component?

I have the following component:

import React from 'react';
import PropTypes from 'prop-types';
import IconButton from '@material-ui/core/IconButton';
import TextField from '@material-ui/core/TextField';
import ClearIcon from '@material-ui/icons/Clear';

const InputSearch = ({ onClearSearch, onSearch, ...searchProps }) => {
    const { id, value } = searchProps;

    const onClear = (event) => {
         onClearSearch(event, id);
    };

     return (
        <TextField
            id={id}
            name={id}
            onChange={onSearch}
            value={value}
            InputProps={{
                endAdornment: value && (
                    <IconButton
                        className={classes.searchIcon}
                        onClick={onClear}
                    > 
                        <ClearIcon fontSize={'small'} color={'primary'} />
                    </IconButton>
                ),
             }}
        />
    );
};

InputSearch.propTypes = {
    onClearSearch: PropTypes.func.isRequired,
};

export default InputSearch;

As you can see, I'm trying to apply a required validation using propTypes. But then, when I try to use the component without the onClearSearch function, no error is being shown:

<InputSearch
     value={searchBy}
     onSearch={handleSearch}
     />

So what I'm doing wrong?

Upvotes: 1

Views: 45

Answers (1)

Avani Bataviya
Avani Bataviya

Reputation: 770

Your code is right... you can open developer tool of chrome by pressing F12 -> go to Console and you can see prop type error

for more detail you can see https://blog.logrocket.com/validating-react-component-props-with-prop-types-ef14b29963fc/

If you want your project give prop-type error in terminal then you have to setup eslint in your project.

Upvotes: 1

Related Questions