JavaScript Archives - Code Snippets https://www.mohamedkadi.com/snippet/category/javascript/ Fast Coding without memorizing Wed, 25 Sep 2024 11:03:02 +0000 en-US hourly 1 https://wordpress.org/?v=6.7 216119969 React Code Snippets: A Guide to Handling Lists, Arrays, and Events https://www.mohamedkadi.com/snippet/react-code-snippets/ https://www.mohamedkadi.com/snippet/react-code-snippets/#respond Thu, 28 Mar 2024 17:29:23 +0000 https://www.mohamedkadi.com/snippet/?p=132 In this article, we’ll dive into some common React code snippets that focus on handling lists, arrays, and events. Whether you’re sorting arrays, filtering objects, or managing user interactions, these snippets will provide a clear understanding of how React handles these common tasks. 1. Working with Lists & Arrays in React Assigning an Array to […]

The post React Code Snippets: A Guide to Handling Lists, Arrays, and Events appeared first on Code Snippets.

]]>
In this article, we’ll dive into some common React code snippets that focus on handling lists, arrays, and events. Whether you’re sorting arrays, filtering objects, or managing user interactions, these snippets will provide a clear understanding of how React handles these common tasks.

1. Working with Lists & Arrays in React

Assigning an Array to a Variable and Sorting It

Let’s start with a basic array of programming languages:

// Start

const languages = ['C', 'Python', 'Javascript', 'Php', 'Typescript', 'Kotlin'];
languages.sort();  // Sorts alphabetically by default
const listItems = languages.map(language => <li>{language}</li>);

// End

In this example, we first declare an array of programming languages. Using the sort() method, we sort the array alphabetically. We then map over the array to generate a list of <li> elements for each language.

2. Handling Arrays of Objects in React

Sorting an Array of Objects

When working with arrays of objects, you might want to sort them based on object properties. Here’s how you can do it:

  // Start

const frameworks = [
  {id: 0, name: 'React', tech: 'Frontend'},
  {id: 1, name: 'Angular', tech: 'Frontend'},
  {id: 2, name: 'Vue.js', tech: 'Frontend'},
  {id: 3, name: 'NodeJS', tech: 'Backend'},
  {id: 4, name: 'Express.js', tech: 'Backend'}
];

// Sorting by framework name in ascending order
frameworks.sort((a, b) => a.name.localeCompare(b.name));

// Sorting in descending order
frameworks.sort((a, b) => b.name.localeCompare(a.name));

// Mapping sorted objects to list items
const objectItems = frameworks.map(framework => (
  <li key={framework.id}>
    {`${framework.name}: ${framework.tech}`}
  </li>
));

// End

In this example, we sort the array of objects by the name property using localeCompare, which ensures that sorting works with non-English characters too. Then we map over the sorted array to create a list of items displaying both the name and tech type (Frontend or Backend).

3. Filtering Arrays

Sometimes you may need to filter out specific items from an array. In this case, we’ll filter out the frontend frameworks from our array:

// Start

const frontendFrameworks = frameworks.filter(framework => framework.tech === 'Frontend');

const frontendItems = frontendFrameworks.map(framework => (
  <li key={framework.id}>
    {`${framework.name}: ${framework.tech}`}
  </li>
));

// End

Here, the filter() method filters out frameworks where tech is "Frontend", and the result is used to display only the frontend frameworks.

4. Default Props & PropTypes

React components can be enhanced by specifying default props and PropTypes to ensure type checking and default behavior. Here’s a quick example:

// Start

List.propTypes = {
  category: PropTypes.string,
  items: PropTypes.arrayOf(PropTypes.shape({
    id: PropTypes.number,
    name: PropTypes.string,
    tech: PropTypes.string
  }))
};

List.defaultProps = {
  category: "category",
  items: []
};
// End

In this snippet, we define PropTypes to validate the type of props passed to the List component. We also set defaultProps to give default values if none are provided.

5. Handling Events in React

React allows us to handle events efficiently, even with parameters or changing the DOM. Let’s look at two different use cases.

Event with Parameter

Here’s a simple example where we track the number of clicks on a button:

let count = 0;
const handleClick = (name) => {
  if(count < 3) {
    count++;
    console.log(`${name}, you clicked me ${count} times`);
  } else {
    console.log(`${name}, stop clicking me`);
  }
};

const Button = () => (
  <button onClick={() => handleClick("momo")}>Click me</button>
);

In this example, the handleClick function takes a name as a parameter. It tracks the number of clicks and logs a different message once the count exceeds 3.

6. Changing Properties on Event Trigger

In this example, we modify the button’s properties based on user interaction, and we toggle the visibility of an HTML element:

let active = false;

const handleClick = (e) => {
  if (!active) {
    e.target.textContent = "I am active";
    e.target.style.backgroundColor = "green";
    e.target.style.color = "white";
    e.target.style.padding = "10px 30px";
    active = true;

    document.getElementById('heading3').style.display = "none";
  } else {
    e.target.textContent = "I am deactivated";
    e.target.style.backgroundColor = "red";
    e.target.style.color = "white";
    e.target.style.padding = "10px 30px";
    active = false;

    document.getElementById('heading3').style.display = "block";
  }
};

Here, we check if a button is active or not. If it’s not active, we update its text and style. We also hide a heading element by changing its display property. When the button is clicked again, the button text and style revert, and the heading is made visible again.

Conclusion

React makes it easy to work with arrays, objects, and events. Sorting, filtering, and mapping arrays, along with managing event-driven updates to the UI, are key skills for any React developer. These snippets provide a solid foundation for handling these tasks in your projects.

The post React Code Snippets: A Guide to Handling Lists, Arrays, and Events appeared first on Code Snippets.

]]>
https://www.mohamedkadi.com/snippet/react-code-snippets/feed/ 0 132