user4790067
user4790067

Reputation: 451

Navigate to a component without changing url in ReactJS

I want to navigate from one component to another ,as in, upon a button click in component1 , we should be redirected to component2 without having to use this.navigation.navigate() as this requires specifying a new URL. I want the URL to remain same and I do not want to use react-router. Is there a way to do this?

The behavior ideally is that a button click in component1 will render component2 in the place of component1 which takes up the whole screen. In a way component1 would cause component2 to render. But I do not want the user to have access to component2 directly. Hence I do not want a change in the URL. Would containers still be the way to go?

Upvotes: 0

Views: 4077

Answers (1)

oklas
oklas

Reputation: 8220

You need to return that component witch appropriate by your condition like this:

class Container extends Component {
  render() {
    let cond = this.props.condition
    return (
      { cond ? <Component1/> : <Component2/> }
    )
  }
}

EDIT: switch may be like this:

class Component1 extends Component {
  render() {
    return (
      <button onClick={this.props.onDone}/>
    )
  }
}


class Container extends Component {
  constructor(props) {
    this.state = { done: false }
  }

  render() {
    let cond = this.state.done
    return (
      { cond ?
        <Component1 onDone={()=>this.setState({done:true})}/> :
        <Component2/>
      }
    )
  }
}

Upvotes: 2

Related Questions