3

I have a functional component inside which I have a button. I want to call a functional component when that button is clicked.

When we click Submit button the Preview button shows up and when the user clicks the preview button then Preview functional component is called.

const Form =(props)=>{

handlePreview=(e)=>{
    e.preventDefault();

    return <Preview/>
  }

return(
<input name="email" type="text"/>
<button type="submit" onClick={props.handleSubmit}>Submit</button><br/>
  {props.render&& 
   <button type="submit" onClick={handlePreview}>Preview</button>
  }

)
}

When I click the Submit button the Preview Button shows up but when I click the Preview Button it doesnt navigate to the <Preview> functional component

1
  • You should include your Preview component into the Form if you wish to render them conditionally, and control via state Commented Jul 10, 2019 at 1:38

1 Answer 1

8

To render component you should return it from function Form. If you return any component from event handler it will be ignored.

So to show <Preview/> component you should create local state. In functional components it can be done with React Hooks like below

const Form =(props)=>{
    const [isPreviewShown, setPreviewShown] = useState(false);

    handlePreview=(e)=>{
        e.preventDefault();

        setPreviewShown(true); // Here we change state
    }

    return(
        <input name="email" type="text"/>
        <button type="submit" onClick={props.handleSubmit}>Submit</button><br/>
        {props.render&& 
            <button type="submit" onClick={handlePreview}>Preview</button>
        }
        {isPreviewShown && <Preview/>}

    )
}
Sign up to request clarification or add additional context in comments.

1 Comment

Before sharing answers in hooks, I suggest to clarify on the ReactJS version that OP is using because many ReactJS projects still doesn't support hooks, just in case OP wondering why your answer isn't working. (I've upvoted btw)

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.