Skip to content Skip to sidebar Skip to footer

Load New A New Component OnKeyPress - Reactjs

I'm trying to load a new component i have made when i press the button 'Enter'. I have implemented the onKeyPress function successfully as follows. class SearchBar extends Comp

Solution 1:

What you can do is to establish Routes for you component and then dynamically change the route with this.context.router like

class SearchBar extends Component {

        constructor(props) {

            super(props);

            this.handleKeyPress = this.handleKeyPress.bind(this);

        }


        handleKeyPress(e) {

            if (e.key === 'Enter') {

                console.log("load new page");
                this.context.router.push('/home');
            }
        }

        render() {

            return (

                <div className="search_bar_div">

                    <div className="search_bar_internal_div">

                        {/* Search bar for desktop and tablets */}
                        <span className="Rev_logo">Revegator</span>

                        <input type="search" placeholder="Search here" className="search_bar"
                               onKeyPress={this.handleKeyPress}/>

                    </div>

                 </div>
              )
       }
}


SearchBar.contextTypes = {
  router: React.PropTypes.func.isRequired
};

Solution 2:

How are you handling the route in your Router definitions in the index? It might not work if you don't have a parent route that then renders it's children, rather than having just a bunch of named routes.


Solution 3:

for example, my index would look like this

ReactDOM.render(
  <Provider store={store}>
    <Router history={browserHistory}>
      <Route path='/' component={App}>
        <IndexRoute component={Welcome} />
        <Route path='/signin' component={SignIn} />
        <Route path='/signout' component={SignOut} />
        <Route path='/register' component={SignUp} />
        <Route path='/map' component={Map} />
        <Route path='/dashboard' component={RequireAuth(Dashboard)} />
        <Route path='/admin' component={RequireAdmin(Admin)} />
        <Router path='*' component={Welcome} />
      </Route>
</Router>

with my main App component (the top level Route under Router)

render() {
return (
  <div>
  <Header />
    {this.props.children}
  </div>
)
}

this means that '/' is rendered from the App component, and any route declared after the '/' will be rendered INTO the app component, instead of it's own page.


Post a Comment for "Load New A New Component OnKeyPress - Reactjs"