Home > Net >  How to return a component in React
How to return a component in React

Time:04-09

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?

CodePudding user response:

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>))

CodePudding user response:

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
    
    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 >
            <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>

CodePudding user response:

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>))

  • Related