1

I have developed an component which displays the table of data and an button which should leads to the another component to create an new item in the list.

I tried different approaches to get this component redirection on button click but not able to achieve this kind of redirection on button click event. With Router the thing is navigation always stays on the page.

Is this possible to achieve this task in spfx webpart with reactjs? please suggest.

2 Answers 2

1

You can use a state object to toggle what is rendered. When a state object is updated it will force a re-render of the component:

<div>
{
  this.state.showNewForm ? 
    <NewFormComponent onCompleted={()=>this.setState({ showNewForm: false})} /> 
   : 
    <ListComponent /> 
}
  <button onClick={this.setState({ showNewForm: true });>Create new item</button>
</div>

Reference: State and Lifecycle - React

0

I will highly recommend using react-router-dom. Below is a sample code from here.

import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import { Route, Link, BrowserRouter as Router, Switch } from 'react-router-dom'
import App from './App'
import Users from './users'
import Contact from './contact'
import Notfound from './notfound'const routing = (
  <Router>
    <div>
      <ul>
        <li>
          <Link to="/">Home</Link>
        </li>
        <li>
          <Link to="/users">Users</Link>
        </li>
        <li>
          <Link to="/contact">Contact</Link>
        </li>
      </ul>
      <Switch>
        <Route exact path="/" component={App} />
        <Route path="/users" component={Users} />
        <Route path="/contact" component={Contact} />
        <Route component={Notfound} />
      </Switch>
    </div>
  </Router>
)ReactDOM.render(routing, document.getElementById('root'))

Here, you have Users and Contact components. Using react router, you can switch between the components via URL path. It provides a lot more functionality like passing arguments to component. You can go through the before mentioned link.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.