I have MUI Alert box in my application. I need to change inside message with href URL. when I set the herf
tag it shows as text, I want to display it as link.
From the blow code, when I click Button, it display href as text. May I know how to display it as html link?
import * as React from 'react';
import { useState } from 'react';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import { Alert} from '@mui/material';
import Typography from '@mui/material/Typography';
export default function BasicAlerts() {
const [message, setMessage] = useState('Form Loaded');
// function to handle the click event on the link
const handleLinkClick = () => {
console.log("inside function")
var u='<a href="https://www.google.com">Visit Google</a>'
setMessage("changed : " +u)
};
return (
<Stack sx={{ width: '100%' }} spacing={2}>
<Alert variant="outlined" severity="info">
This is an info alert — check it out!
<Typography>
<br/>
{message}{' '}
<br/>
</Typography>
</Alert>
<Button onClick={handleLinkClick}>Change</Button>
</Stack>
);
}
Here is the code share link: https://codesandbox.io/s/ecstatic-smoke-zjp82h
Your state is actually a string also on your click event your setMessage("changed : " +u)
output is a string. so your anchor html is become an normal text under <Typography />
tag.
You can set your href
through your click event and based on your href you can show your output as an normal typgraphy
or a anchor link
.
For Example :
const [href, setHref] = useState("");
const [message, setMessage] = useState("Form Loaded");
// function to handle the click event on the link
const handleLinkClick = () => {
console.log("inside function");
var url = "https://google.com";
setHref(url);
setMessage("visit Google");
};
<Alert variant="outlined" severity="info">
This is an info alert — check it out!
<Typography>
<br />
{href ? (
<a id="anchor" href={href}>
{message}
</a>
) : (
message
)}
</Typography>
</Alert>