Five Code Challenges in ReactJS

I have been learning React.js for some time now and just a few days back I came across this blog post with 5 code challenges, from the dead simple Hello World to reading users from an API using Axios. Below are the chanllenges and my solutions.

Challenge #1 – Hello World

Create a React app in Codepen that outputs Hello World to the screen.

class App extends React.Component {
  render() {
    return (
      <p>Hello World React!</p>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('app'));

See the Pen Hello World React by Esau Silva (@esausilva) on CodePen.0

Challenge #2 – Hello Visitor

This app takes the input from the text input field and outputs your input in realtime to the screen. The input should be your name, because it’s cool seeing your name on a page. This is likely the first time you’ll see how cool React really is.

class VisitorName extends React.Component {
  handleChange = (e) => {
    this.props.updateVisitorName(e.target.value);
  };
  
  render() {
    return (
      <input type='text' placeholder='Enter your name' 
             value={this.props.visitorName}
             onChange={this.handleChange} />
    );
  }
}
// *********************************************************
class App extends React.Component {
  state = {
    visitorName: ''
  };

  updateVisitorName = (name) => {
    this.setState({ visitorName: name });
  };

  clearText = () => {
    this.setState({ visitorName: '' })
  };

  render() {
    return (
      <div>
        <VisitorName visitorName={this.state.visitorName}
                     updateVisitorName={this.updateVisitorName} />
        <button type='button' onClick={this.clearText}>Clear</button>
        <br />
        <p>Hello, {this.state.visitorName || 'visitor'}</p>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('app'));

See the Pen Hello Visitor by Esau Silva (@esausilva) on CodePen.0

Challenge #3 – Fizz Buzz

Everyones favorite junior developer interview question.

“Can you build FizzBuzz? Show me!”

Don’t get frustrated, this is quite a bit more challenging. You’ll need to create increment and decrement buttons.

class FizzBuzz extends React.Component {
  state = {
    fizzBuzz: '',
    counter: 0
  };

  isFizzBuzz = () => {
    let i = this.state.counter;
    let fb = this.state.fizzBuzz;
    
    if (i % 3 === 0) { fb += 'Fizz, ' }
    if (i % 5 === 0) { fb += 'Buzz, ' };
    if (i % 5 && i % 3) { fb += i + ', ' };
    
    this.setState({ fizzBuzz: fb });
  };

  increment = () => {
    this.setState({ counter: ++this.state.counter });
    this.isFizzBuzz();
  };

  decrement = () => {
    this.setState({ counter: --this.state.counter });
    this.isFizzBuzz();
  };

  render() {
    return (
      <div>
        <p>Click buttons to create FizzBuzz</p>
        <button type='button' onClick={this.increment}>+</button>{ }
        <button type='button' onClick={this.decrement}>-</button><br /><br />
        {this.state.fizzBuzz}
      </div>
    );
  }
}

ReactDOM.render(<FizzBuzz />, document.getElementById('app'));

See the Pen Fizz Buzz by Esau Silva (@esausilva) on CodePen.0

Challenge #4 – Markdown Previewer

The last 2 challenges can be found over at FreeCodeCamp. Here is the link to the freeCodeCamp challenge. Build a Markdown Previewer.

class MarkdownPreview extends React.Component {
  state = {
    textarea: ''
  };

  componentWillMount() {
    this.setState({ textarea: 'Heading\n=======\n\nSub-heading\n-----------\n \n### Another deeper heading\n \nParagraphs are separated\nby a blank line.\n\nLeave 2 spaces at the end of a line to do a  \nline break\n\nText attributes *italic*, **bold**, \n`monospace`, ~~strikethrough~~ .\n\nShopping list:\n\n  * apples\n  * oranges\n  * pears\n\nNumbered list:\n\n  1. apples\n  2. oranges\n  3. pears\n\nThe rain---not the reign---in\nSpain.\n\n *[Esau Silva\'s blog](https://esausilva.com)*' })
  }

  handleChange = (e) => {
    this.setState({ textarea: e.target.value })
  };

  render() {
    return (
      <div>
        <textarea rows="40" cols="50" onChange={this.handleChange}>{this.state.textarea}</textarea>
        <div dangerouslySetInnerHTML={{__html: marked(this.state.textarea)}} />
      </div>
    );
  }
}

ReactDOM.render(<MarkdownPreview />, document.getElementById('app'));

See the Pen Markdown Previewer by Esau Silva (@esausilva) on CodePen.0

Challenge #5 – Camper Leaderboard

For the final challenge you will build a Leaderboard app. You will need to access the Leaderboard data using the provided endpoints. You will need to grab data for pretty much every React app you build so this one is important.

Here is the link to the freeCodeCamp challenge. Build a Camper Leaderboard.

Pro-tip: Use Axios to perform your GET requests to access the Leaderboard data.

/**
  Table body component
*/
class Table extends React.Component {
  handleSort = (e, sort) => {
    this.props.handleSort(sort);
  };
  
  renderCampers = (key, count) => {
    const camper = this.props.campers[key];
    return(
      <tr key={key}>
        <td>{count}</td>
        <td>
          <a href={`https://www.freecodecamp.com/${camper.username}`} target='_blank'>
            <img src={camper.img} />
            {camper.username}
          </a>
        </td>
        <td className='center'>{camper.recent}</td>
        <td className='center'>{camper.alltime}</td>
      </tr>
    )
  };

  render() {
    return (
      <div>
        <table>
          <caption>Leaderboard</caption>
          <tr>
            <th>#</th>
            <th>Camper Name</th>
            <th onClick={(e) => this.handleSort(e, 'recent')}><a href='javascript:void(0)'>Points in the past 30 days</a></th>
            <th onClick={(e) => this.handleSort(e, 'alltime')}><a href='javascript:void(0)'>All time points</a></th>
          </tr>
          {Object.keys(this.props.campers).map((key, i) => {
            return this.renderCampers(key, ++i);
          })}
        </table>
      </div>
    );
  }
}

/**
  Container
*/
class CamperLeaderboard extends React.Component {
  state = {
    campers: [],
    sort: 'recent'
  };

  getData = (sort) => {
    let url = `https://fcctop100.herokuapp.com/api/fccusers/top/${sort}`
    const self = this;
    axios.get(url)
      .then(function (response) {
        self.setState({ campers: response.data });
        //console.log(self.state.campers);
      })
      .catch(function (error) {
        console.log(error);
      });
  };

  componentWillMount() {
    this.getData(this.state.sort);
  }

  handleSort = (sort) => {
    this.setState({ sort }, () => this.getData(this.state.sort));
  };

  render() {
    return (
      <div>
        <p>Click links in table header to sort</p>
        <Table campers={this.state.campers} 
              handleSort={this.handleSort} />
      </div>
    );
  }
}

ReactDOM.render(<CamperLeaderboard />, document.getElementById('app'));

See the Pen Camper Leaderboard by Esau Silva (@esausilva) on CodePen.0

Visit the original blog post (How I learned React and how you can too) to see the author’s solutions.



 

Esau Silva
Software Engineer at Region One ESC
Full Stack Software Engineer working with Microsoft technologies, ReactJS is awesome and avid Brazilian Jiu-Jitsu practitioner
If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed.
Share