Search code examples
reactjstypescriptmaterial-uistyled-components

ListItemButton onclick wont fire on the first click when using my own component as children


I have issues understanding why this onclick cares what the children is and how it works

  <ListItemButton onClick={() => onClickResult(q)}>
       <Typography variant="body1">{highlighted}</Typography>
  </ListItemButton>

this examples where Typography from mui is beeing used works as aspected (first click triggers onClick)

but using allmost the same code but another children:

          <ListItemButton
            onClick={() => onClickResult(q)}
          >
            <HighlightText text={highlighted} />
          </ListItemButton>

where Highlighted is defined before the return():

  const HighlightText = ({ text }: { text: string }) => {
    const splitText = text.split('}');
    const hasHighlights = splitText.length > 1;
    if (!hasHighlights) {
      return <Typography variant="body1">{text}</Typography>;
    }
    return (
      <StyledHighlightText>
        <Typography variant="body1">{splitText[0].replace('{', '')}</Typography>
        <StyledHighlightTextBold variant="body1">
          {splitText[1]}
        </StyledHighlightTextBold>
      </StyledHighlightText>
    );
  };

and the on click:

  const onClickResult = (query: string) => {
    window.location.href = `${url}?q=${encodeURIComponent(
      query,
    )}&origin=PHRASE_SUGGEST`;
  };

Now i have to click twice before the onClick gets fired. I see absolutely no reason for it to take 2 clicks instead of 1 now in order to trigger click


Solution

  • I found a workaround: create method instead of a component

          <ListItemButton
            onClick={() => onClickResult(q)}
          >
            {getHighlightText(highlighted)}
          </ListItemButton>
    

    and

      const getHighlightText = (text: string) => {
        const splitText = text.split('}');
        const hasHighlights = splitText.length > 1;
        if (!hasHighlights) {
          return <Typography variant="body1">{text}</Typography>;
        }
        return (
          <StyledHighlightText>
            <Typography variant="body1">{splitText[0].replace('{', '')}</Typography>
            <StyledHighlightTextBold variant="body1">
              {splitText[1]}
            </StyledHighlightTextBold>
          </StyledHighlightText>
        );
      };
    

    I still have no clue why using the component-way doesn't work