1

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.

2 Answers 2

1

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>
  );
}
Sign up to request clarification or add additional context in comments.

1 Comment

can even do {isNumber ? <Component1/> : <Component2/>
1

You can do like this

const MainComp = () => {


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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.