Event onclick doesn't happen NextJS - javascript

index.js:
function Home () {
return <div>
<html>
<head>
<title>Site</title>
</head>
<body>
<div class= 'v5_3' onclick = "func_click()"></div>
</body>
</html>
</div>
}
function func_click() {
alert('ALERT!!');
}
export default Home ; func_click
I'm developing locally with nextjs through the npm run dev that I learned through this link
(19:00 ate 21:50) however when I click on the button that is inside the div 'v5_3' which in turn is in the main.css file:
.v5_3 {
width: 150px;
height: 50px;
color: white;
background: rgb(5, 5, 5);
opacity: 1;
position: absolute;
top: 30px;
left: 1171px;
border-top-left-radius: 30px;
border-top-right-radius: 30px;
border-bottom-left-radius: 30px;
border-bottom-right-radius: 30px;
}
,that is being imported by the _app.js file
:
import './main.css'
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
Which in turn are all in the pages folder:
does not execute my alert, which is in function
func_click():
function func_click() {
alert(' ALERT!!');
}
I'm not able to do this interaction with JavaScript, how to solve this?

I believe you know that Next.js is a React.js framework. This means that you need to handle clicks the way React handles them.
Start by defining the function inside the component. This is not mandatory but adds cohesion to your code.
Then reference to the function by using onClick camelcased and the bracket syntax onClick={funcClick} to bind the click function to the div.
For the class use className instead. These elements are not (yet) HTML elements and should be seen as object. With that in mind className is a property of an HTMLElement object.
function Home() {
const funcClick = () => {
alert("ALERT!!");
};
return (
<div>
<html>
<head>
<title>Site</title>
</head>
<body>
<div className="v5_3" onClick={funcClick}></div>
</body>
</html>
</div>
);
}
export default Home;

Related

Properties background image not working [React]

I'm trying to set the background image of a div depending on the value of a component property, the background doesn't show, however it does show when I harcode the background-image property in the css file.
Here is the component code :
import React, { Component } from "react";
import "./Banner.css";
export default class Banner extends Component {
render() {
const style = {
backgroundImage: `url("${this.props.image}")`,
};
return (
<div className="banner" style={style}>
Chez vous, partout et ailleurs
</div>
);
}
}
Here is the Banner.css file:
.banner {
/* background-image: url("../assets/images/moutains.png"); */
background-size: cover;
height: 170px;
border-radius: 20px;
text-align: center;
vertical-align: middle;
line-height: 170px;
font-size: 2.5rem;
color: #fff;
}
In the parent component:
<Banner image="../assets/images/moutains.png" text="" />
EDIT: Complete code and assets here: https://github.com/musk-coding/kasa
codesandbox: https://codesandbox.io/s/github/musk-coding/kasa
Thanks in advance for your help
Since, you are trying to access the image directly in your Component using the inline CSS. You must move your image to the public folder.
CODESANDBOX LINK: https://codesandbox.io/s/image-relative-path-issue-orbkw?file=/src/components/Home.js
Code Changes:
export default class Home extends Component {
render() {
const imageURL = "./assets/images/island-waves.png";
return (
<div className="container">
<div className="slogan" style={{ backgroundImage: `url(${imageURL})` }}>
Chez vous, partout et ailleurs
</div>
<Gallery />
</div>
);
}
}
NOTE: From React Docs, you can see the ways to add images in Component. create-reac-app-images-docs. But since you want an inline CSS, in that case we have to move our assets folder into the public folder to make sure that the image is properly referenced with our component.

Webcomponents is re-initializing every time while working with Vue js

I have created a webcomponent for a generic input boxes that i needed across multiple projects.
the design functionality remains same only i have to use switch themes on each projects.so i have decided to go on with webcomponents.One of the projects is based on Vue Js.In Vue js the DOM content is re-rendered while each update for enabling reactivity. That re-rendering of vue template is reinitializing my custom webcomponent which will result in loosing all my configurations i have assigned to the component using setters.
I know the below solutions. but i wanted to use a setter method.
pass data as Attributes
Event based passing of configurations.
Using Vue-directives.
using v-show instead of v-if
-- Above three solutions doesn't really match with what i am trying to create.
I have created a sample project in jsfiddle to display my issue.
Each time i an unchecking and checking the checkbox new instances of my component is creating. which causes loosing the theme i have selected. (please check he active boxes count)
For this particular example i want blue theme to be displayed. but it keep changing to red
JSFiddle direct Link
class InputBox extends HTMLElement {
constructor() {
super();
window.activeBoxes ? window.activeBoxes++ : window.activeBoxes = 1;
var shadow = this.attachShadow({
mode: 'open'
});
var template = `
<style>
.blue#iElem {
background: #00f !important;
color: #fff !important;
}
.green#iElem {
background: #0f0 !important;
color: #f00 !important;
}
#iElem {
background: #f00;
padding: 13px;
border-radius: 10px;
color: yellow;
border: 0;
outline: 0;
box-shadow: 0px 0px 14px -3px #000;
}
</style>
<input id="iElem" autocomplete="off" autocorrect="off" spellcheck="false" type="text" />
`;
shadow.innerHTML = template;
this._theme = 'red';
this.changeTheme = function(){
this.shadowRoot.querySelector('#iElem').className = '';
this.shadowRoot.querySelector('#iElem').classList.add(this._theme);
}
}
connectedCallback() {
this.changeTheme();
}
set theme(val){
this._theme = val;
this.changeTheme();
}
}
window.customElements.define('search-bar', InputBox);
<!DOCTYPE html>
<html>
<head>
<title>Wrapper Component</title>
<script src="https://unpkg.com/vue"></script>
<style>
html,
body {
font: 13px/18px sans-serif;
}
select {
min-width: 300px;
}
search-bar {
top: 100px;
position: absolute;
left: 300px;
}
input {
min-width: 20px;
padding: 25px;
top: 100px;
position: absolute;
}
</style>
</head>
<body>
<div id="el"></div>
<!-- using string template here to work around HTML <option> placement restriction -->
<script type="text/x-template" id="demo-template">
<div>
<div class='parent' contentEditable='true' v-if='visible'>
<search-bar ref='iBox'></search-bar>
</div>
<input type='checkbox' v-model='visible'>
</div>
</script>
<script type="text/x-template" id="select2-template">
<select>
<slot></slot>
</select>
</script>
<script>
var vm = new Vue({
el: "#el",
template: "#demo-template",
data: {
visible: true,
},
mounted(){
let self = this
setTimeout(()=>{
self.$refs.iBox.theme = 'blue';
} , 0)
}
});
</script>
</body>
</html>
<div class='parent' contentEditable='true' v-if='visible'>
<search-bar ref='iBox'></search-bar>
</div>
<input type='checkbox' v-model='visible'>
Vue's v-if will add/remove the whole DIV from the DOM
So <search-bar> is also added/removed on every checkbox click
If you want a state for <search-bar> you have to save it someplace outside the <search-bar> component:
JavaScript variable
localStorage
.getRootnode().host
CSS Properties I would go with this one, as they trickle into shadowDOM
...
...
Or change your checkbox code to not use v-if but hide the <div> with any CSS:
display: none
visibility: hidden
opacity: 0
move to off screen location
height: 0
...
and/or...
Managing multiple screen elements with Stylesheets
You can easily toggle styling using <style> elements:
<style id="SearchBox" onload="this.disabled=true">
... lots of CSS
... even more CSS
... and more CSS
</style>
The onload event makes sure the <style> is not applied on page load.
activate all CSS styles:
(this.shadowRoot || document).getElementById("SearchBox").disabled = false
remove all CSS styles:
(this.shadowRoot || document).getElementById("SearchBox").disabled = true
You do need CSS Properties for this to work in combo with shadowDOM Elements.
I prefer native over Frameworks. <style v-if='visible'/> will work.. by brutally removing/adding the stylesheet.

Dynamic image is not loaded via :src

I am working on a simple Vue app, using vue-cli and webpack for that purpose.
So basicly i have 2 components, a parent and a child component ~
like this:
<template>
<div class="triPeaks__wrapper">
<div class="triPeaks">
<tri-tower class="tower"></tri-tower>
<tri-tower class="tower"></tri-tower>
<tri-tower class="tower"></tri-tower>
</div>
<div class="triPeaks__line">
<tower-line :towerLine="towerLineCards" />
</div>
<tri-pack />
</div>
</template>
the towerLineCards is the important thing there, it is a prop that is passed to the tower-line component, it is basicly a array with 10 elements, it is a array with 10 numbers that are shuffled, so it can be something like that:
[1,5,2,6,8,9,16,25,40,32]
this array is create via beforeMount on the lifecycle.
On the child component:
<template>
<div class="towerLine-wrapper">
<div class="towerLine">
<img v-for="index in 10" :key="index" class="towerLine__image" :src="getImage(index)" alt="">
</div>
</div>
</template>
<script>
export default {
props: {
towerLine: {
type: Array,
required: true
}
},
method: {
getImage (index) {
return '#/assets/images/cards/1.png'
}
}
}
</script>
<style lang="scss">
.towerLine {
display: flex;
position: relative;
top: -90px;
left: -40px;
&__image {
width: 80px;
height: 100px;
&:not(:first-child) {
margin-left: 3px;
}
}
}
</style>
the issue is with the :src image that i am returning via the getImage(), this way it is not working. If i change to just src it works just fine, i did this way just to test, because the number in the path should be dynamic when i got this to work.
What is wrong with this approach? any help?
Thanks
Firstly, you should use a computed property instead of a method for getImage().
And to solve the other problem, you could add require(YOUR_IMAGE_PATH) when you call your specific image or put it inside /static/your_image.png instead of #/assets/images/cards/1.png.

CSS doesn't apply to a component

I have a react component that is wrapped up in div:
AccountLogin.jsx:
import './AccountLogin.css';
export default observer(() => (
<div className="content">
Something here
</div>
));
AccountLogin.css:
.content {
color: blue;
background-color: blue;
margin: 500px;
}
But the css doesn't apply to my rendered component AccountLogin.
Any ideas why that could happen?
Looking at rfx-stack source, I can see that files suffixed with .global.css are imported in global scope where as others are imported as css-modules.
So you can either rename your file to AccountLogin.global.css or use the imported class name:
import styles from './AccountLogin.css';
Within component:
<div className={styles.content}>...</div>

'React' is defined but never used

I am following the official reactjs instructions to create a sample app. My node version is 6.9.0.
I created sample react app which is supposed to display a empty tic tac toe table according to the official website using following instructions:
npm install -g create-react-app
create-react-app my-app
cd my-app
changed to my-app directory
removed the default files inside the source directory as directed. Now
my index.js looks like this
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
Then I ran yarn start
But all I see is blank screen no tic tac toe table. And couple warnings in the console saying
Compiled with warnings.
./src/index.js
Line 1: 'React' is defined but never used no-unused-vars
Line 2: 'ReactDOM' is defined but never used no-unused-vars
Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.
You missed last parts in steps 4 & 5:
Add a file named index.css in the src/ folder with this CSS code.
Add a file named index.js in the src/ folder with this JS code.
index.css
body {
font: 14px "Century Gothic", Futura, sans-serif;
margin: 20px;
}
ol, ul {
padding-left: 30px;
}
.board-row:after {
clear: both;
content: "";
display: table;
}
.status {
margin-bottom: 10px;
}
.square {
background: #fff;
border: 1px solid #999;
float: left;
font-size: 24px;
font-weight: bold;
line-height: 34px;
height: 34px;
margin-right: -1px;
margin-top: -1px;
padding: 0;
text-align: center;
width: 34px;
}
.square:focus {
outline: none;
}
.kbd-navigation .square:focus {
background: #ddd;
}
.game {
display: flex;
flex-direction: row;
}
.game-info {
margin-left: 20px;
}
index.js
class Square extends React.Component {
render() {
return (
<button className="square">
{/* TODO */}
</button>
);
}
}
class Board extends React.Component {
renderSquare(i) {
return <Square />;
}
render() {
const status = 'Next player: X';
return (
<div>
<div className="status">{status}</div>
<div className="board-row">
{this.renderSquare(0)}
{this.renderSquare(1)}
{this.renderSquare(2)}
</div>
<div className="board-row">
{this.renderSquare(3)}
{this.renderSquare(4)}
{this.renderSquare(5)}
</div>
<div className="board-row">
{this.renderSquare(6)}
{this.renderSquare(7)}
{this.renderSquare(8)}
</div>
</div>
);
}
}
class Game extends React.Component {
render() {
return (
<div className="game">
<div className="game-board">
<Board />
</div>
<div className="game-info">
<div>{/* status */}</div>
<ol>{/* TODO */}</ol>
</div>
</div>
);
}
}
// ========================================
ReactDOM.render(
<Game />,
document.getElementById('root')
);
You should create some component/element/, maybe style it, then call ReactDOM to render your component to the underlying html and then you will have it.
React is used to handle JSX and creation of React component
ReactDOM in your simple case will be used to render created element to dom.
See here : https://reactjs.org/blog/2015/10/01/react-render-and-top-level-api.html
So ading something like
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
to your code, you will get something if in your index.html there is element with id="root" inside <body> tag
This simply means your project has eslint configured to catch unused variables.
If you use JSX or anything React within that file the warning will go away just like suggested by zmii in his answer.
But i am writing this answer because someone showed me their code and they were facing the same problem.
Their code :
import React from 'react';
const person = () => {
return "<h2>I am a person!</h2>"
};
export default person;
The problem in the above code was that while returning, he used double quotes. So instead of JSX, it was returning string and therefore they were getting error that React was never not used.
Conclusion: Syntax are important so keep in mind, specially if you are starting out.
Hope this helps someone.
ESlint needs to be configured to work with React JSX. This excellent article has all the details.

Categories