Home > front end >  Render a component by clicking a link in React
Render a component by clicking a link in React

Time:05-27

I'm building a story in storybook, but that isn't too relevant to the question at hand. Basically, I need to build a situation where I have an anchor tag that, when clicked, opens a dialog box/modal window. The dialog is a component, <Dialog />. I'm mocking it up as something that looks like:

<a onclick={launches Dialog component}>Click Me</a>

This seems like a simple question and I just don't know the answer. I appreciate the help!

CodePudding user response:

You'd have a few ways to achieve your needs.

  1. Using useState and conditional rendering
const [open, setOpen] = useState(false)
<a onClick={() => setOpen(true)}>Click Me</a>
{open && <MyComponent />}
  1. Using useState and css
const [open, setOpen] = useState(false)
<a onClick={() => setOpen(true)}>Click Me</a>
{/* You could use visibility instead of display */}
<MyComponent style={{display: open ? 'block' : 'none'}} />
  1. In case of a new window, I'd recommend using some external library such as react-new-window
  • Related