user7801216
user7801216

Reputation:

Call a React component to show up like an alert function

I have a react component which shows a message:

Here's the code:

import React, { PropTypes } from 'react';

const Message = props => {
  const { type, msg } = props;

  if (type === 'success') {
    return (<div>{msg}</div>);
  } else {
    return null;
  }
};

Message.PropTypes = {
  type: PropTypes.string.isRequired,
  msg: PropTypes.string.isRequired,
};

export default Message;

//This component is called like this from index.js:

<Message type="success" msg="This is a Message" />

My question is...How can I call the component like I would call a function.

For example:

if (function is success then) {
  //Show the Message Component
}

How can I do this with React?

Upvotes: 0

Views: 2974

Answers (1)

Henrik Andersson
Henrik Andersson

Reputation: 47172

If the if clause is within another React component you'd just render it,

class AnotherReact extends Component {
    render() {
        let alert = success ? <Message /> else '';
        return (<div>{ alert }</div>);   
    }
}

Otherwise if not in a React component then you would have to use ReactDOM.render().

if (is success) {
    ReactDOM.render(<Message />, document.querySelector());
}

Upvotes: 1

Related Questions