How to add a html element inside a exported const - html

I have a export const with a big text, and in the middle I want to add a hyperlink element, but this is not working.
My code:
const myEmail = 'example#example.com'
export const EXAMPLE = `Example of email: ${myEmail}`
Where I import:
import React, { FC } from 'react'
import { EXAMPLE } from '../../constants/ui.constants'
const Example: FC<{}> = () => {
return <div>{EXAMPLE}</div>
}
export default Example
But this shows like this:
How can I show the email like this ?
(this was edit through inspect tools)

You can use dangerouslySetInnerHTML, but you have to be very sure that whatever you are injecting is not something the user has control over, otherwise you will be introducing a XSS vulnerability.
import React, { FC } from 'react'
import { EXAMPLE } from '../../constants/ui.constants'
const Example: FC<{}> = () => {
return <div dangerouslySetInnerHTML={EXAMPLE} />
}
export default Example

Related

UseParallax ref hook not working with components in NextJs

I'm trying to use the useParallax hook on an element in my js file. I'm using NextJs with ReactJs as well as styled components. I used the hook in the following way:
Mainland.js
import React, { useEffect, useRef } from 'react';
import styled, { keyframes } from 'styled-components';
import { useParallax } from 'react-scroll-parallax';
const Mainland = () => {
const { parallaxRef } = useParallax({ speed: 20 }); // set up the hook to use with useRef
const StyledDiv = styled.div`` //Styled Component
return (
<StyledDiv ref={parallaxRef}>
...
</StyledDiv>
The error here is the following:
Error: You must assign the ref returned by the useParallax() hook to an HTML Element.
So I tried to use it without styled components and straight to an HTML element and it still didn't work.
Extra Information: I used the parallax provider in my _app.js file in the following way:
import Layout from '../Components/Layout';
import '../styles/globals.css';
import { ParallaxProvider } from 'react-scroll-parallax';
function MyApp({ Component, pageProps, ...appProps }) {
const isLayoutNeeded = [`/Contact`].includes(appProps.router.pathname);
return (
<>
<Layout state={isLayoutNeeded}>
<ParallaxProvider>
<Component {...pageProps} />
</ParallaxProvider>
</Layout>
</>
);
}
export default MyApp;
Additional info:
https://react-scroll-parallax.damnthat.tv/docs/usage/hooks/use-parallax
Install module inside your project folder. That fixed it for me
npm i install react-scroll-parallax
The useParallax hook returns { ref, controller, element }.
So try this:
const { ref: parallaxRef } = useParallax({ speed: 20 });

Create a HTML element with ReactJs

I'm trying to learn ReactJS and now I'm making a small project that consists of a button that every time I click it, it will show an html element (as I still couldn't get the button to work, I haven't created the element yet, so the element it should create is an h1), but when I click the button nothing happens, could anyone help me? (sorry for any spelling mistakes, I'm still learning English)
This is my code:
import Container from "./App.style";
import Button from "./Components/Button/Button.jsx";
const App = () => {
const createElement = () => {
return(
<h1>Hey</h1>
)
}
return (
<>
<Container>
<h1>Criador De Elementos</h1>
<Button onClick={ createElement }>Criar Elemento</Button>
</Container>
</>
);
}
export default App;
import React from "react";
import StylesButton from "./Button.style";
const Button = ( {onClick, children} ) => {
return (
<StylesButton onClick={ onClick }> { children } </StylesButton>
);
}
export default Button;
Looks like you your code is correct. But my question is where you want to that h1 element. If you want h1 to Your DOM than you must create an h1 to your DOM and control value of h1 by using state (by Using useState Hook).
if you want to render your h1 element then you can do like this.
import {useState} from 'react';
import Container from "./App.style";
import Button from "./Components/Button/Button.jsx";
const App = () => {
const [heading,setHeading] = useState("");
const createElement = () => {
setHeading("Hey");
}
return (
<>
<Container>
<h1>Criador De Elementos</h1>
<Button onClick={ createElement }>Criar Elemento</Button>
<h1>{heading}</h1>
</Container>
</>
);
}
export default App;
import React from "react";
import StylesButton from "./Button.style";
const Button = ( {onClick, children} ) => {
return (
<StylesButton onClick={ onClick }> { children } </StylesButton>
);
}
export default Button;

Data not appearing after axios fetch (ReactJs)

Good day guys, i'm having a little trouble trying to req data from axios and showing it up at ReactJS, i'm able to console.log the data, but when i try to render it at the page, it simply dot not appear, could someone please lend me a hand? i will let the code and a print of the console.log, it's probably a newbie mistake since i'm new to ReactJs and JSON, but i would be very grateful if someone could explain!
CODE:
import Image from 'next/image'
import { useRouter } from 'next/router'
import React, { Component, useState } from 'react'
import ReactDOM from 'react-dom'
import { useHistory ,useLocation } from 'react-router-dom';
import axios from 'axios'
const options = {
method: 'GET',
headers: {
'Authorization': 'OAuth oauth_consumer_key="key", oauth_signature_method="PLAINTEXT", oauth_signature="2CC8D92526EE859C90AABB1F09F3B719&"'}
};
class Page extends React.Component {
state= {
motorData: [],
opa: []
};
componentDidMount() {
const make = "fiat"
axios.get(`https://api.trademe.co.nz/v1/Search/Motors/Used.json?make=${make}`, options)
.then(res => {
const cars = res.data;
console.log(cars)
this.state.motorData.push(cars.List[0].StartPrice)
console.log(this.state.motorData)
})
}
render() {
return <div>
Data:{this.state.motorData}
</div>
}
}
export default Page ```
Thank you guys so much in advance!
Instead of doing a push to your state, you need to use setState. Something like this:
componentDidMount() {
const make = "fiat"
axios.get(`https://api.trademe.co.nz/v1/Search/Motors/Used.json?make=${make}`, options)
.then(res => {
const cars = res.data;
this.setState(state => ({
motorData: [...state.motorData, cars.List[0].StartPrice]
});
})
}
Also, your motorData is an array, right? so in your render method you might want to loop in that array because you won't be able to print it I think. You should do something like this:
render() {
return (
<div>
Data:
// Adjust the return to be what you want it to render and
// don't forget to add a `key` property to the element you
// will return
{this.state.motorData.map(data => data)}
</div>
)
}
The problem is that, to set the state correctly, you should use setState, in this way:
this.setState((state) => ({ motorData: [...state.motorData, cars.List[0].StartPrice]}))
Using setState tells React that the state is changed and it have to re-render the component.

If and why the CSS should be put outside the react function components(near the imports)?

I just meet a problem that could not load the CSS inside react function component with material UI. Though I fixed it, I am still curious about the reason.
In the beginning, I write something like this, where I put both makeStyles and useStyles inside the function component. Then, I find that the class name is correctly assigned to the element, but no css is loaded.
import makeStyles from "material-UI"
import styles from "styles.js"
export default function alertPage() {
const useStyles = makeStyles(styles);
const classes = useStyles();
const [alert, setalert] = React.useState();
const showAlert = () => {
setalert(<p className={classes.text}></p>)
}
return (
<button onClick={showAlert}></button>
{alert}
)
}
Then, I put makeStyles outside the function, everything works correctly.
import makeStyles from "material-UI"
import styles from "styles.js"
const useStyles = makeStyles(styles);
export default function alertPage() {
const classes = useStyles();
const [alert, setalert] = React.useState();
const showAlert = () => {
setalert(<p className={classes.text}></p>)
}
return (
<button onClick={showAlert}></button>
{alert}
)
}
Then, I tried this code putting both inside function component again, but return the HTML directly, which still works.
import makeStyles from "material-UI"
import styles from "styles.js"
export default function alertPage() {
const useStyles = makeStyles(styles);
const classes = useStyles();
return (
<p className={classes.text}></p>
)
}
Then, I check the react official site and find that they always put CSS outside the function component, but not getting any sentences mentioned that this is required or why.
My guess is that I misunderstand the scope of the const or how CSS is actually loaded in the browser. If anybody could tell me the reason, or which piece of knowledge I missed, like js, ts, react, or how the browser works?
Thanks!
From the Material UI docs, you should have something like the below:
import React from 'react';
import { makeStyles } from '#material-ui/core/styles';
const useStyles = makeStyles({
root: {
// Your styles
},
});
export default function Hook() {
const classes = useStyles();
// Rest of your code
}
If you have styles in a correctly formatted import, you should be able to add them directly in the makeStyles declaration:
const useStyles = makeStyles(styles)

Dynamic color of text input in react

I want text entry to be highlighted with different colors depending on the character entered.
My hunch is that it is possible to do this by adding <span> elements with the appropriate styling inside of a contenteditable div.
Is there a better way?
Hi Please check this example. I used material-ui
import React, {useState} from 'react';
import Box from '#material-ui/core/Box';
import TextField from "#material-ui/core/TextField";
export default function BackgroundColor() {
const [text, setText] = useState('');
const [color, setColor] = useState('');
function changeHandler(event) {
setText(event.target.value);
if(event.target.value.toLowerCase() === 'a'){
setColor("primary.main");
}
else if(event.target.value.toLowerCase() === 'b'){
setColor("secondary.main");
}
else if(event.target.value.toLowerCase() === 'c'){
setColor("error.main");
}
else{
setColor("info.main");
}
}
return (
<div>
<TextField id="standard-basic" label="Standard" helperText="Type A or B or C" onChange={changeHandler} />
<Box color={color}>
{text}
</Box>
</div>
);
}
Depending on the complexity, you can also consider using Ace Editor
import React, { useState } from "react";
import AceEditor from "react-ace-builds";
import "./yamlHighlightRules";
import "ace-builds/src-noconflict/theme-github";
import "ace-builds/src-noconflict/ace";
import "./styles.css";
export default function App() {
const [text, setText] = useState("This is the most amazing initial text.");
const handleChange = input => {
setText(input);
};
return (
<div className="App">
<AceEditor
mode="yaml"
theme="github"
name="editor"
fontSize={15}
showPrintMargin={true}
showGutter={false}
highlightActiveLine={false}
value={text}
onChange={handleChange}
setOptions={{
showLineNumbers: true,
tabSize: 2,
readOnly: false
}}
height={"600px"}
width={"100%"}
/>
</div>
);
}
And then I edited an existing set of yaml highlighting rules, it's easier not starting from scratch.
import ace from "ace-builds/src-min-noconflict/ace";
import "ace-builds/src-noconflict/mode-text";
ace.define("ace/mode/yaml_highlight_rules", [], function(require, exports) {
const oop = require("../lib/oop");
const TextHighlightRules = require("./text_highlight_rules")
.TextHighlightRules;
const YamlHighlightRules = function() {
this.$rules = {
start: [
{
token: "highlight",
regex: /amazing/
}
]
};
this.normalizeRules();
};
oop.inherits(YamlHighlightRules, TextHighlightRules);
exports.YamlHighlightRules = YamlHighlightRules;
});
The token is your css class. Just add the prefix ace_ to it. Then you define a regular expression to determine what gets that class.
.ace_highlight {
background-color: yellow;
}
Here is a codesandbox where you can see it working.
And here are the docs on defining your own modes.