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 challenges and my solutions.

[topads][/topads]

Challenge #1 – Hello World

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

lass 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.

const VisitorName = props => {
  return (
    <input type='text' placeholder='Enter your name' 
      value={props.visitorName}
      onChange={props.updateVisitorName} />
  );
}

class App extends React.Component {
  state = {
    visitorName: ''
  };

  updateVisitorName = (e) => {
    this.setState({ visitorName: e.target.value });
  };

  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: 1
  };

  isFizzBuzz = () => {
    const 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((prevState, props) => ({ counter: ++prevState.counter }));
    this.isFizzBuzz();
  };

  decrement = () => {
    this.setState((prevState, props) => ({ counter: --prevState.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\n**[Visit my Revamped Markdown Editor](https://esausilva.github.io/live-markdown-editor/)**\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](http://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 presentational component
*/
const Table = ({ campers, handleSort }) => {
  const renderCampers = (key, count) =>  {
    const camper = 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>
    )
  };

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

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

  getData = async (sort) => {
    let url = `https://fcctop100.herokuapp.com/api/fccusers/top/${sort}`
    const response = await axios
      .get(url)
      .catch(err => console.error('Error in Axios', err));
    if (response) this.setState({ campers: response.data });
  };

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

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

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

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

/*
To get the top 100 campers for the last 30 days: https://fcctop100.herokuapp.com/api/fccusers/top/recent.
To get the top 100 campers of all time: https://fcctop100.herokuapp.com/api/fccusers/top/alltime.
*/

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.


Consider giving back by getting me a coffee (or a couple) by clicking the following button:

[bottomads][/bottomads]

Spread the love

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.