1

Basically i would like the user to click a button which will add a <Message /> component to the page. and they can keep clicking the button and more <Message /> components will be created.

Pseudo Code

render() {
    return (
        <button onClick={this.addMessage}></button>
        <Message />
        //basically a new message component would spawn here so it would look like this if the person clicked the button 3 times

        <Message /> 
        <Message /> 
        <Message /> 

    );

}

addMessage = () => {
   create new Message component
}
3
  • 2
    Hint... every click adds to an array in state and you then map that array in the render() and each iteration creates a new <Message/> Commented May 9, 2020 at 21:19
  • 1
    As @charlietfl says, each action by the user sets a new array with one extra item in it :) Commented May 9, 2020 at 21:20
  • 2
    Does this answer your question? React.js: How to append a component on click? Commented May 9, 2020 at 21:20

1 Answer 1

4

Use a state object to do what you want. For example,

const [messages, setMessages] = useState([]);
const wasClick = (data) => {
    setMessages([...messages, data]);
}

and then in render function

messages.map(message=><Message message={message}/>)
Sign up to request clarification or add additional context in comments.

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.