1

i got this problem in the console, i tried refactoring my code and 2 things broke:

the links routing doesnt work when i dont pass in a callback function, and i got this console error error too

so the questions are:

1.how do i fix the console error?

  1. whats wrong with my 'exact to' template string? doesnt change the url,

the component:

const {  NavLink } = ReactRouterDOM;
    export function SingleNavLink(props){
        const {url,name,onCategoryChange}=props
        const linkorbutton=(onCategoryChange)?`exact to=${url}`:`onClick={onCategoryChange(name.toLowerCase())}`
        return(
            <NavLink  linkorbutton>
              {name}
            </NavLink>
        )
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Kontantin
  • 67
  • 1
  • 8
  • 1
    You're trying to treat a string as props to a JSX tag. You need to create a hash and destructure that, e.g., `{...dynamicProps}`. – Dave Newton Apr 28 '20 at 19:20
  • Also, a prop without a value is just a shorthand for `prop={true}`. – Emile Bergeron Apr 28 '20 at 19:21
  • can u give a written example? code is not very long , i dont know anything about hashing unfortunately – Kontantin Apr 28 '20 at 19:21
  • Does this answer your question? [How do I conditionally add attributes to React components?](https://stackoverflow.com/questions/31163693/how-do-i-conditionally-add-attributes-to-react-components) – Emile Bergeron Apr 28 '20 at 19:22

1 Answers1

2

onClick must be a function. Also the syntax for onClick is incorrect because template string makes it a string which it is not.

The best solution is to store the linkProps as an object based on condition and use spread syntax to pass it to Navlink

const {  NavLink } = ReactRouterDOM;
export function SingleNavLink(props){
    const {url,name,onCategoryChange}=props
    const linkProps= onCategoryChange ? {exact: true, to: url} : { onClick: () => {onCategoryChange(name.toLowerCase())}}
    return(
        <NavLink  {...linkProps}>
          {name}
        </NavLink>
    )
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400