Snippset

Snipps

...see more

When building tree structures in React, you might see this warning:

"Encountered two children with the same key..."

This usually happens when your component is rendering a list or tree and uses the same key value for multiple items. React requires that keys be unique among siblings to correctly track changes.

The Problem

In some apps, a tree of items is built using IDs like id, targetId, and parentId. A common mistake is using a field like targetId as the unique key — but if that field isn't truly unique, React throws an error.

Also, when building the tree structure, developers often assume that parentId matches a node’s id, but sometimes it actually matches others like targetId — and since targetId isn't unique, that causes lookup problems.

The Fix

Here’s how to correctly build the tree and avoid duplicate keys:

  1. Use id as the unique key — it's meant to be unique and stable.
  2. Create a dictionary keyed by id.
  3. Build a helper map from targetId to nodes — since targetId isn't unique, store an array of nodes per targetId.
  4. When assigning children, match parentId to the corresponding targetId, and attach the node to all matches (if multiple).

Here’s a simplified version of the corrected tree builder:

function buildTree(nodes) {
  const updatedNodes = nodes.map(node => ({
    ...node,
    id: String(node.id),
    targetId: String(node.targetId),
    parentId: String(node.parentId),
    children: [],
  }));

  const targetIdToNodes = {};
  updatedNodes.forEach(node => {
    if (!targetIdToNodes[node.targetId]) {
      targetIdToNodes[node.targetId] = [];
    }
    targetIdToNodes[node.targetId].push(node);
  });

  const rootNodes = [];

  updatedNodes.forEach(node => {
    if (node.parentId === '0') {
      rootNodes.push(node);
    } else {
      const parents = targetIdToNodes[node.parentId];
      if (parents) {
        parents.forEach(parent => {
          parent.children.push(node);
        });
      }
    }
  });

  return rootNodes;
}

In your React rendering, always use node.id for the key:

<TreeNode key={node.id} node={node} />

Takeaway

Always make sure your keys in React are unique and stable. And when building a tree, know what your parentId is pointing to — it can make or break your structure.

...see more

JSX may look like HTML, but it’s actually JavaScript. When used correctly, it brings power and clarity to React development.

Why Use JSX?

  • It’s familiar to anyone who has written HTML.
  • You can mix logic and layout using {} for JavaScript expressions.
  • JSX is compiled into fast and efficient React code.

Key JSX Rules

  • Use className instead of class.
  • Self-closing elements like <img />.
  • Wrap multiple elements in one parent: <div> or <>.

Example:

function Greeting() {
  return <h1>Hello, world!</h1>;
}

Common Mistakes

  • Forgetting to close tags.
  • Using class instead of className.
  • Returning multiple sibling elements without a wrapper.
...see more

When using ref in React, especially with forwardRef, it's important to understand how ref works — and how it doesn't.

The Problem

You might see this warning in your console:

ref is not a prop. Trying to access it will result in undefined being returned...

This usually happens when you try to declare ref in your component's propTypes or access it like a normal prop (props.ref). But ref is a special prop in React. It doesn't behave like other props.

✅ The Correct Way to Use ref

When using forwardRef, React gives the ref as the second argument of your function. Here's what that looks like:

const MyComponent = forwardRef(function MyComponent(props, ref) {
  // use ref directly
});

Don't try to access ref through props.ref. That won't work.


❌ Don't Do This

MyComponent.propTypes = {
  // This will trigger a warning!
  ref: PropTypes.any,
};

React doesn't pass ref through the normal props object, so it shouldn’t be validated with propTypes.


The Fix

  • Use ref only via the second argument in forwardRef.
  • Remove ref from propTypes.

This will prevent the warning and adhere to React best practices.

...see more

If you're using TinyMCE in a React app and want to provide users with a way to remove all data-* attributes from their content, you can create a custom toolbar button to do just that.

Why do this?

data-* attributes are often added by frameworks, plugins, or tracking tools. In some cases, you might want to remove these before saving or publishing content, especially for clean, production-ready HTML.

How to Add the Button

You can use TinyMCE’s setup function to add a custom button with a mop-like icon to your toolbar. Here's how:

import { Editor } from '@tinymce/tinymce-react';

function MyEditor({ content, contentChange, onEditorInit }) {
  return (
    <Editor
      value={content}
      onEditorChange={(newValue) => contentChange(newValue)}
      onInit={onEditorInit}
      init={{
        height: 500,
        menubar: false,
        plugins: 'code',
        toolbar: 'undo redo | mopCleaner | bold italic underline | code',
        setup: (editor) => {
          editor.ui.registry.addIcon('mopCleanerIcon', `
            <svg width="24" height="24" viewBox="0 0 24 24">
              <path d="M12 2v14" stroke="currentColor" stroke-width="2"/>
              <path d="M8 16h8l1 4H7l1-4z" fill="currentColor"/>
            </svg>
          `);

          editor.ui.registry.addButton('mopCleaner', {
            icon: 'mopCleanerIcon',
            tooltip: 'Remove all data-* attributes',
            onAction: () => {
              const currentContent = editor.getContent();
              const cleanedContent = currentContent.replace(/\sdata-[\w-]+="[^"]*"/g, '');
              editor.setContent(cleanedContent);
            },
          });
        },
      }}
    />
  );
}

How it works:

  • The button removes all HTML attributes that match the pattern data-something="value".
  • It works even when multiple data-* attributes are in a single tag.
  • You can customize the icon or tooltip to match your app's style.

Tip:

To support edge cases, such as attributes with single quotes or no values, you can enhance the regex as needed.

...see more

TinyMCE is a popular rich text editor used to add content-editing capabilities to web apps. When working with React, TinyMCE provides an official wrapper that makes integration quick and easy.

Here’s how to set it up in a React project:

1. Install the Package

Use npm:

npm install @tinymce/tinymce-react

2. Basic Usage

Import the component and render it:

import { Editor } from '@tinymce/tinymce-react';

function MyEditor() {
  return (
    <Editor
      initialValue="<p>Start typing...</p>"
      init={{
        height: 300,
        menubar: false,
        plugins: 'link image code',
        toolbar: 'undo redo | formatselect | bold italic | link image | code',
      }}
    />
  );
}

This will render a fully functional rich text editor inside your React component.

3. Handling Content Changes

You can capture changes to the editor content like this:

<Editor
  onEditorChange={(newContent) => {
    console.log(newContent); // Save or process the content here
  }}
/>

Tips:

  • TinyMCE is highly customizable with plugins, themes, and custom toolbars.

  • You can host TinyMCE locally or use the cloud version.

  • It supports custom buttons, icons, and content filtering.


Learn More:

Visit TinyMCE React Docs for advanced configuration options.

...see more

Application Insights doesn’t store the original .NET LogLevel (like Debug or Trace) — it only stores SeverityLevel, which combines them. To make your logs easier to filter and analyze, you can add LogLevel as a custom property using a TelemetryInitializer.

Example:

public class LogLevelInitializer : ITelemetryInitializer
{
    public void Initialize(ITelemetry telemetry)
    {
        if (telemetry is TraceTelemetry trace &&
            telemetry is ISupportProperties props &&
            !props.Properties.ContainsKey("LogLevel"))
        {
            props.Properties["LogLevel"] = trace.SeverityLevel switch
            {
                SeverityLevel.Verbose => "TraceOrDebug",
                SeverityLevel.Information => "Information",
                SeverityLevel.Warning => "Warning",
                SeverityLevel.Error => "Error",
                SeverityLevel.Critical => "Critical",
                _ => "Unknown"
            };
        }
    }
}

Integration

Register the initializer in your app:

services.AddSingleton<ITelemetryInitializer, LogLevelInitializer>();

Now, every trace will include a LogLevel key in customDimensions.

...see more

It’s best practice to tailor logging levels per environment (Development, Staging, Production) by using environment-specific configuration files like appsettings.Development.json or appsettings.Production.json.

Example for Development (verbose logging):

{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "Microsoft": "Information",
      "System": "Warning",
      "YourAppNamespace": "Trace"
    }
  }
}

Example for Production (concise logging):

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "Microsoft": "Warning",
      "System": "Warning",
      "YourAppNamespace": "Information"
    }
  }
}

By adjusting log levels per environment, you can capture detailed diagnostics during development while reducing noise and performance impact in production.

...see more

Application Insights uses a fixed enum called SeverityLevel with 5 levels: Verbose, Information, Warning, Error, and Critical.

When logging in .NET using ILogger, the log level (such as Debug, Information, or Error) is internally mapped to Application Insights’ SeverityLevel. However, the mapping isn’t one-to-one — and by default, you can lose detail.

SeverityLevel Mapping Overview

Application Insights uses this enum:

Application Insights SeverityLevel Typical .NET LogLevel
Verbose (0) Trace / Debug
Information (1) Information
Warning (2) Warning
Error (3) Error
Critical (4) Critical

Both Trace and Debug are treated as Verbose, which means they can’t be distinguished once sent to Application Insights.

 

Tip: Add LogLevel as a Custom Property

To retain the original LogLevel, consider using a TelemetryInitializer to add it manually — so you can later filter logs by both SeverityLevel and original LogLevel.

...see more

ASP.NET Core allows you to customize logging behavior per provider, such as Console or Application Insights. This is useful when you want different verbosity or volume controls depending on the sink.

Example:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "Microsoft": "Warning",
      "System": "Warning",
      "YourAppNamespace": "Trace"
    },
    "Console": {
      "LogLevel": {
        "Default": "Information",
        "YourAppNamespace": "Debug"
      }
    },
    "ApplicationInsights": {
      "LogLevel": {
        "Default": "Error"
      }
    }
  }
}
  • Console logs are more verbose for development and debugging (Information and Debug).
  • Application Insights only logs errors to reduce telemetry volume and cost.

Use per-provider overrides when you want finer control over logging destinations.

...see more

Looking to save time and work more efficiently? With just a few well-crafted prompts, ChatGPT can handle tasks that usually take hours—giving you more time to focus on what truly matters. Whether you're writing emails, preparing reports, or summarizing complex information, these prompt ideas will help you get the job done faster and more effectively.

 

1. Draft Emails With Clear Messaging
Prompt:
"Draft a professional email to inform [recipient] about [issue, update, or change]. Ensure the message is clear, concise, and respectful, and include any necessary next steps or follow-up information."
Helps communicate important messages effectively.

 

2. Write Polished, Professional Emails
Prompt:
"Write a well-structured and polite email to [recipient's name] about [topic]. Include the following key points: [key point 1], [key point 2], [key point x]. Use a formal tone suitable for business communication."
Saves time while ensuring your communication stays professional.

 

3. Summarize Lengthy Documents Quickly
Prompt:
"Please review the attached document (or link) and provide a clear summary. Highlight the main ideas, key conclusions, and any important recommendations in a structured format."
Perfect for turning lengthy reports into quick overviews.

 

4. Turn Notes Into Actionable Tasks
Prompt:
"Based on the following meeting notes: [paste notes], create a list of actionable tasks. Assign each task to a relevant team member and suggest reasonable deadlines."
Helps teams stay organized and accountable after discussions.

 

5. Design a Presentation with Ease
Prompt:
"Using the content from the attached document, create a PowerPoint presentation. Include slides for: introduction, main findings, data insights, and conclusion. Keep the design simple and professional."
Great for professionals who need quick, effective visuals.

 

6. Explain Code in Simple Terms
Prompt:
"Explain what the following code does in plain, beginner-friendly language. Also, suggest improvements for better performance or readability. [insert code]"
Useful for developers and learners alike.

 

7. Create Reports from Raw Data
Prompt:
"Analyze the data in the attached spreadsheet and create a professional report. Focus on important metrics such as sales growth, customer acquisition cost, and profit margin over the last quarter. Include visual summaries if helpful."
Ideal for transforming data into executive summaries or board-ready reports.

 

8. Generate Customer Support Templates
Prompt:
"Create customer support response templates for frequently asked questions about [product or service]. Include helpful steps for troubleshooting, refund procedures, and upgrade options."
Supports faster response times with consistent messaging.

 

9. Research a Topic and Summarize
Prompt:
"Research the topic '[insert topic]' and provide a short, clear summary. Include recent developments, key facts, and major organizations or individuals involved. Keep the explanation easy to understand."
Saves time on background research and fact-finding.

 

10. Create Content Plans or Blog Outlines
Prompt:
"Create a detailed blog post outline on the topic '[insert topic]'. Include a compelling title, section headings, bullet points for each section, and links to relevant sources or data."
Perfect for content creators and marketers.

Add to Set
  • .NET
  • Agile
  • AI
  • ASP.NET Core
  • Azure
  • C#
  • Cloud Computing
  • CSS
  • EF Core
  • HTML
  • JavaScript
  • Microsoft Entra
  • PowerShell
  • Quotes
  • React
  • Security
  • Software Development
  • SQL References
  • Technologies
  • Testing
  • Visual Studio
  • Windows
 
Sets