Projects

Fun Animal Facts

This is my first project that uses React to create an interactive app that gives you animal facts when you click an animal.

Result

Method

Set Up

Before I did anything I had to do the initial setup and configuration for a React application's rendering process.


    //initial set up
    const container = document.getElementById('app');
    const root = ReactDOM.createRoot(container);
    const title = '';                
            

Create Dictionary of Animal Facts

The first thing I created was a dictionary where all the animal facts are stored, in order to call upon them depending on what animal is selected.


    const animals = {
        dolphin: {
            image: 'dolphin.png',
            facts: ['Dolphins have been shown to give distinct names to each other!', 'Dolphins are known to display their own culture!', 
                'Dolphins have two stomachs!']
        },
        lobster: {
            image: 'lobster.png',
            facts: ['Lobsters taste with their legs!', 'Lobsters chew with their stomachs!', 'Lobsters can live as long as 100 years.']
        },
        starfish: {
            image: 'starfish.png',
            facts: ['Starfish can have up to 40 arms!', 'Starfish have no brain and no blood!', 'Starfish can regenerate their own arms!']
        }
    };    
            

Image Creation

Next, I used JSX to but together the main display for the app, and placed the individual animals on top.


    //Create a background
    const background = (
        <img
        className='background'
        alt='ocean'
        src='./ocean.png' />
    )
    //image array for each animal
    const images = [];
    for (const animal in animals){
        const image = (
            <img 
            onClick={displayFact}
            key={animal} 
            className='animal'
            alt={animal}
            src={`./${animals[animal].image}`}
            aria-label={animal}
            role='button'/%gt
            )
            images.push(image)
    };
    //Ternary conditional to decide on title
    const animalFacts = (
        <div>
            <h1>
                {title === '' ? 'Click an animal for a fun fact!' : title}
            </h1>
            {background}
            <p id='fact'></p>
            <div className='animals'>{images}</div>
        </div>
    );    
            

Event Listener Function

Finally, I created an event listener function that would, depending on what animal you click, would give you a random fact from the dictionary about that animal.


    //event listener function
    function displayFact(e) {
        const animal = e.target.alt;
        const index = Math.floor(Math.random() * animals[animal].facts.length);
        const funFact = animals[animal].facts[index];
        const p = document.getElementById('fact');
        p.innerHTML = funFact;
    }
    //Render code
    root.render(animalFacts);