0

How can I render an element when I clicked the function in ReactJS?

I have a component Notifications and imported to the main component. I coded a function to check the validation and render the Notifications component:

const submit = () => {
      if (name === '' || email === '' || phone === '' || subject === '' || message === '') {
        setStateOfInput();
        //I don't know how to render the <Notifications/> from here
      }
      else if (email.indexOf('@') === -1) {
        //And here
        setStateOfInput();
      }
...

I used return ( <Notifications/> ) but it wasn't working!

I'm new to ReactJs so thanks for all your help!

1
  • You don't "render it from there". The typical approach would be to set a flag that indicates it should be rendered then conditionally render it along with the rest of the component. Commented Apr 19, 2022 at 19:53

1 Answer 1

1

I would set a state inside to control of rendering your component but if you really want to return in function you can do something like that

const submit = () => {
      if (name === '' || email === '' || phone === '' || subject === '' || message === '') {
        setStateOfInput();
        return <Notifications />
      }
      else if (email.indexOf('@') === -1) {
        setStateOfInput();
        return <SomeComponent />
      }
...

Inside the main return of the component you can call this function

    return (.......

<div>{submit()}</div>

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