Zuk Levinson
Zuk Levinson

Reputation: 149

How to condition the rendering of React function with hooks?

I'm trying to condition the rendering of different React function components, according to specific parameters.

For example, I want to render ComponentA if an input field includes only a number, or ComponentB otherwise. I use a switch case that returns the component that corresponds with the right case. Important to mention that each of the components includes different hooks (different numbers of states e.g).

When I run the program, I get an error that a different number of hooks is rendered. What is the right way to accomplish this? Currently I'm using a class that extends the React Component class since it does not use Hooks, but I'm trying to find a solution that allows me to use them.

Upvotes: 1

Views: 176

Answers (2)

edemaine
edemaine

Reputation: 3120

You only need to use the same number of hooks within each component. If you return a component (rather than directly calling the component function), each component can use a different number of hooks. For example:

function Component(props) {
  const [field, setField] = useState('');
  const isNumber = !isNaN(parseInt(field)); // or however you want to detect numbers
  //...
  return (
    <div>
      <input value={field} onChange={(e) => setField(e.target.value)}/>
      {isNumber && <Component1/>}
      {!isNumber && <Component2/>}
    </div>
  );
}

Upvotes: 1

user3766327
user3766327

Reputation: 21

You can do like this

const MainComp = () => {


const customRender = () =>{
    if(val==1){
        return(<Comp1>)
    }else{
    return (<Comp2>)
    }
}

return(
    <div>
        {customRender}
    </div>
)
}

Upvotes: 1

Related Questions