1

Can I create a new component on a onClick-event in reactjs. I've tried this:

My component where the click event occurs:

...
<li onClick={this.edit.bind(this)}><span className="glyphicon glyphicon-pencil"></span> Edit entry</li>
...

This is the edit method:

 edit(event) {
        return <CreateFreightEntryModal key={"freightEditModal" + this.state.freight.ID} openOnStartup="true" modalId={"freightEditModal" + this.state.freight.ID} />
    }

No error is thrown, but the component is not being created. Doing I something wrong or is this not really recommended?

3
  • The onlick function is not editing the state at all, you're just returning a component. You should have the edit function toggle an 'edit' state that causes the CreateFreightEntryModal component to be rendered instead of whatever is normally there. Commented Aug 24, 2017 at 11:00
  • 1
    where you are expecting that returned element will get rendered? use a state bool and onclick of edit button use setState and update that with true, use that variable to render the Component, Check the Conditional Rendering part of Doc Commented Aug 24, 2017 at 11:00
  • If this is just 1 element, keep a flag in state and use { flag ? component : null} in render Commented Aug 24, 2017 at 11:01

2 Answers 2

3

In react, showing a modal is a bit tricky because of it's nature.

edit() {
    this.setState({ showModal: true })
}

render() {

    return (
        <div>
             { this.state.showModal && <CreateFreightEntryModal props/> }
        </div>
    )

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

2 Comments

Yeah, I know this solution already, but I have a list of more than 600 entries. I don't want to create for each entry of this list an own component. My thought was to create a component, when an entry is clicked. It saves much loading time not to create foreach entry an own component. Is this possible?
Ok. Now I understand your way. Thanks for your help.
1

You'd better render component with state as @Ozgur GUL stated in the answer.

However, if you have to render something dynamically, you can do like this.

import ReactDOM from 'react-dom';

...
edit() {
  ReactDOM.render(<CreateFreightEntryModal key={"freightEditModal" + this.state.freight.ID} openOnStartup="true" modalId={"freightEditModal" + this.state.freight.ID} />);
}

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.