• Empleos
  • Sobre nosotros
  • Empleos
    • Inicio
    • Empleos
    • Cursos y retos
  • Empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

111
Vistas
How to return a component in React

i have a button component from material UI. What i wanna do is i click a button and it renders to me a new Button on the screen. That's what i did

const [button, setButton] = useState([]);

function addButton(){

 let newObj = {
      button: <Button variant="contained"> A Button</Button>,
    };

 setButton([...button, newObj])

}

And then in the main function return i did

{button.length !== 0 ? (
        button.map((item) => {
          <div>{item.button}</div>;
        })
      ) : (
        <div>Hello</div>
      )}

What am i doing wrong?

over 3 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

When you use a multi-line lambda with braces you need a return...

button.map((item) => {
      return (<div>{item.button}</div>);
    })

Alternatively you can omit the braces...

button.map((item) => (<div>{item.button}</div>))
over 3 years ago · Juan Pablo Isaza Denunciar

0

This answer tries to address the below problem-statement:

But how could i click one button and render as many buttons as i clicked?

The below snippet provides a demo of how a new button may be rendered when user clicks an existing button. This expands on the below comment

Creating a new button on clicking an existing button may be accomplished without needing to hold the component in state.

Please note:

  • It does not store the button elements into the state
  • instead, it merely stores the attributes (like the button-label / text) into the state

Code Snippet

const {useState} = React;

const MyButton = ({
  btnLabel, btnName, handleClick, isDisabled, ...props
}) => (
  <button
    class="myBtn"
    onClick={handleClick}
    name={btnName}
    disabled={isDisabled}
  >
    {btnLabel}
  </button>
);

const MagicButtons = () => {
  const [btnText, setBtnText] = useState("");
  const [disableBtns, setDisableBtns] = useState(false);
  const [myButtons, setMyButtons] = useState(["A Button"]);
  const handleClick = () => setDisableBtns(true);
  return (
    <div>
      {
        disableBtns && (
          <div class="myInput">
            <input
              value={btnText}
              onChange={e => setBtnText(e.target.value)}
            />
            <button
              onClick={() => {
                setMyButtons(prev => ([...prev, btnText]));
                setBtnText("");
                setDisableBtns(false);
              }}
            >
              Add New Button
            </button>
          </div>
        )
      }
      {
        myButtons.map((txt, idx) => (
          <MyButton
            handleClick={handleClick}
            btnName={idx}
            isDisabled={disableBtns ? "disabled" : ""}
            btnLabel={txt}
          />
        ))
      }
    </div>
  );
};

ReactDOM.render(
  <div>
    DEMO
    <MagicButtons />
  </div>,
  document.getElementById("rd")
);
.myBtn { margin: 15px; }
.myInput > input { margin: 15px; }
<div id="rd" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>

over 3 years ago · Juan Pablo Isaza Denunciar

0

You forgot to return the component in the map function like this

{button.length !== 0 ? (
        button.map((item) => {
         return (<div>{item.button}</div>);
        })
      ) : (
        <div>Hello</div>
      )}

the map function with no 'return' keyword must not have the bracket { } like this

   button.map((item) => (<div>{item.button}</div>))

over 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda