Search code examples
reactjscomponents

React component how to add state


I'm using the following to create a tag component:

/components/Tag/index.js

import React from 'react';
import PropTypes from 'prop-types';
import './Tag.scss';

export const Tag = ({ color, ghost, size, label, ...props }) => {
  return (
    <div
      className="tag-primary"
      {...props}
    >
      {label}
    </div>
  );
};

Tag.propTypes = {
  label: PropTypes.string.isRequired,
  onClick: PropTypes.func
};

Tag.defaultProps = {
  color: 'teal',
  size: 'medium',
  onClick: undefined,
};

How can I add a state to my component?


Solution

  • Your component will look like this:

    import React, {useState} from 'react';
    import PropTypes from 'prop-types';
    import './Tag.scss';
    
    export const Tag = ({ color, ghost, size, label, ...props }) => {
    const [state, setState] = useState(false)
    
    // const changeState = () => setState(prev => !prev)
    
      return (
        <div
          className="tag-primary"
          {...props}
        >
          {label}
        </div>
      );
    };
    
    Tag.propTypes = {
      label: PropTypes.string.isRequired,
      onClick: PropTypes.func
    };
    
    Tag.defaultProps = {
      color: 'teal',
      size: 'medium',
      onClick: undefined,
    };

    Function changeState when called, it will change the state to the opposite