Dynamically Render Pages ( without React Router ) - KatyaHorton/Udacity-React-practice GitHub Wiki

Dynamically Render Pages (without React Router):

1

Add new file CreateContact.js as screens in React are just components

import React, { Component }  from 'react'

class CreateContact extends Component {
 render() {
 <div> YOOOO! </div>
}}

export default CreateContact

2

In App.js

import CreateContact from './CreateContact'

render() {
return (
<div>
//rest of the code
<CreateContact />
</div>
)}

3

Could use Router right away, but lets try it with component states first:

Create state to decide which screen to show:

state = {
screen: 'list' //list, createPage
...
}

Make decision in the render() method what to show:

render() {
 return (
   <div>
    {this.state.screen ==='list' && (
     <ListContacts ... />
)} 
    {this.state.screen ==='create' && (
     <CreateContact ... />
)} 
   </div>
)}

4

Add button to change screens (in ListContacts.js just below the input method)

<a 
  href='#create'
  onClick= {() => {} }
  className='add-contact'
> Add contact </a>

5

To be able to change the state of the screen which lives in App component we need to pass a function to the ListContacts component (in App.js file)

onNavigate={() => {
 this.setState({ screen: 'create'})
}}

6

Come back to the ContactList component (to ContactList.js file) to the click handler:

onClick={this.props.onNavigate}}

Which means we click t he button => it call the function => the function changes the state => when the state changes we will switch to the create screen.

⚠️ **GitHub.com Fallback** ⚠️