3

I want to render my ChatBubble component after an amount of time. But it does not return my component. Instead it returns numbers 2 and 3 as a string.

const Conversation = ({data}) => {
  const { messages } = data;

  return (
    <div>
      {
        messages.map(data => {
          return setTimeout(() => {
            return <ChatBubble key={uniqid()} data={data}/>
          }, data.delay);
        })
      }
    </div>
  );
}

export default Conversation;
Thiebe
  • 81
  • 2
  • 5

1 Answers1

6

Cause setTimeout returns the id of the timer. You cannot just return something to react and expect some magic to happen. Instead you probably need a stateful conponent like this:

class Conversation extends React.Component {
  constructor(props) {
    super(props);
    this.state = { messages: [] };
  }

  render() {
    return this.state.messages.map(data => (<ChatBubble {...data} />));
  }

  componentDidMount() {
     const {messages, delay} = this.props.data;
     this.interval = setInterval(() => {
       this.setState(prev => ({ messages: prev.messages.concat(messages.shift()) }));
       if(!messages.length) clearInterval(this.interval);
     }, delay);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }
}
schildi
  • 136
  • 7
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151