make a voting page in svelte, where you can vote on a party, and view the current leader in javascript

To create a voting page in Svelte, you can follow these steps:

  1. Create a Svelte component called Party that represents a single party that users can vote for. This component should take in a name prop that displays the name of the party and an onClick function that is called when the user votes for this party.
<script>
  export let name;
  export let onClick;
</script>

<button on:click={onClick}>{name}</button>
104 chars
7 lines
  1. Create a Svelte component called VotingPage that renders a list of Party components and keeps track of the current leader. This component should have a parties prop that is an array of party names, a votes object that keeps track of the number of votes for each party, and a getLeader function that returns the name of the party with the most votes.
<script>
  import Party from './Party.svelte';

  export let parties;
  
  let votes = {};

  function vote(party) {
    votes[party] = (votes[party] || 0) + 1;
  }

  function getLeader() {
    let max = 0;
    let leader = null;
    for (let party in votes) {
      if (votes[party] > max) {
        max = votes[party];
        leader = party;
      }
    }
    return leader;
  }
</script>

{#each parties as party}
  <Party name={party} onClick={() => vote(party)} />
{/each}

<p>The leader is {getLeader()}</p>
516 chars
30 lines
  1. Use the VotingPage component in your main JavaScript file and provide it with an array of party names as a prop.
index.tsx
import VotingPage from './VotingPage.svelte';

const parties = ['Party A', 'Party B', 'Party C'];

const app = new VotingPage({
  target: document.body,
  props: { parties }
});
178 chars
9 lines

This will render a page with a button for each party that users can click to vote. The current leader will be displayed below the party list and will update as users vote.

gistlibby LogSnag