Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

289
Visualizações
React: Storing functional component in state

Let's say I'd like to render a different child component depending on which button has been clicked:

import { useState } from 'react';

const Bold = ({ text }) => (
    <b>{text}</b>
);

const Italic = ({ text }) => (
    <i>{text}</i>
);

export default function App() {
    const [Component, setComponent] = useState();

    return (
        <>
            <button onClick={() => setComponent(Bold)}>
                Bold
            </button>
            <button
                onClick={() => setComponent(Italic)}
            >
                Italic
            </button>
            {Component && (
                <Component text="I love 🧀 more than life!" />
            )}
        </>
    );
}

I was pretty sure this would work - I set my state item to component's function and render it. But it throws an error:

Uncaught TypeError: Cannot destructure property 'text' of '_ref' as it is undefined.

I checked if it would work without any props in children components, but no - it gives another error when there are no props:

Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: . Did you accidentally export a JSX literal instead of a component?

I don't quite understand why it's happening, but I found a workaround. Instead of setting my state value directly like this:

<button onClick={() => setComponent(Bold)}>

I'm setting it through a setter function:

<button onClick={() => setComponent(() => Bold)}>

It works correctly after that change, but can someone explain why is this happening? Is having a component unpacked somewhere in the template causing problems?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The problem is that setState has two forms.

One where it accepts some object and one that it accepts a function which can work with existing state and returns the new state.

Now, when you pass a component reference, you are actually passing a function to it, and so setState assumes it is the second form, and tries to execute the function in order to get the updated state.

The workaround, as you have found out on your own, is to use the second form, passing a function that when executed will return the component you want.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda