Search code examples
reactjsfluentui-react

Adding Function Reference to IconProps in React App


In my React app I am using react-fluent-ui to handle a lot of the styling. In one block in my class-based component I am using a TextField for a filter element. I have also included a clear icon within the TextField so that the user can click it to clear the text from the input field. What I'm running into a block on is how to include a reference to a function within the block of code where the icon is. Note, the onClick needs to be on the icon specifically, not on the TextField. This is the block of code:

<TextField
  label="ID:"
  defaultValue={this.props.filters.id}
  onChange={this.onFilterById}
  styles={{ root: { maxWidth: 300 } }}
  borderless
  underlined
  iconProps={ clearIconProps }
/>

And the iconProps referenced above look like this:

const clearIconProps = {
  iconName: 'clear',
  cursor: 'pointer',
}

When I try to add the function to the clearIconProps using fat arrow syntax, like so, I have a syntax error: (Parsing error: Unexpected token):

const clearIconProps = {
  onClick={() => clearFilter()},
  iconName: 'clear',
  cursor: 'pointer',
}

I also tried this, but it also causes a syntax error: (Parsing error: Unexpected token):

const clearIconProps = {
  onClick={clearFilter},
  iconName: 'clear',
  cursor: 'pointer',
}

And for the record, at the moment, clearFilter() looks like this:

const clearFilter = () => {
  // Add code to clear field
  console.log('clearFilter() was triggered...');
}

How can I add the function to the icon within the TextField?


Solution

  • As suggested by @NiceToMeetYou, This piece of code is wrong:

    const clearIconProps = {
      onClick={clearFilter}, // This has to be corrected to onClick: clearFilter,
      iconName: 'clear',
      cursor: 'pointer',
    }
    

    Now it becomes something like this:

    const clearIconProps = {
      onClick: clearFilter,
      iconName: 'clear',
      cursor: 'pointer',
    }
    

    We will have to do something like this, to achieve => Note, the onClick needs to be on the icon specifically, not on the TextField. This is the block of code:

    class TextFieldBasicExample extends React.Component {
      constructor(props) {
        super(props);
      }
      
      componentDidMount() {
        const node = ReactDOM.findDOMNode(this);
        if (node instanceof HTMLElement) {
          const child = node.querySelector('i');
          child.addEventListener('click', () => console.log("Hello world"))
          console.log("I am here", child)
        }
      }
      
      render() {
        return (
          <Stack horizontal tokens={stackTokens} styles={stackStyles}>
            <Stack {...columnProps}>
              <TextField label="With an icons" iconProps={iconProps} />
            </Stack>
           </Stack>
        );
      }
    }
    

    Here is the complete code for the same: codepen