i'm learning Javascript and React and i got a problem.
i want to play a javascript function on a jsx files but i don't know where to put it.
i explain:
I want to make a mouseover effect, when "tech-title" is hover, i want to show "tech-text".
In the CSS, visibility is "hidden" for "tech-text"
I want to know what i'm doing wrong ...
thanks a lot ;)
const Resume = () => {
let techTitle = document.querySelectorAll('.tech-title')
let techText = document.querySelectorAll('.tech-text')
function cardDisplay() {
techTitle.addEventListener('mouseover', () => {
techText.style.visibility = 'visible'
})
}
return (
<div className="app-container">
<Profile />
<div className="right-container">
<Navigation />
<div className="display">
<h2 className="exp-title">A propos de moi</h2>
<p className="about-me">
Curieux de nature, je suis à la recherche d'un nouvel environnement de travail pour une première expérience
en tant que Développeur, je suis motivé et prêt à apprendre de nouvelles compétences.
</p>
<h3 className="skills">Skills</h3>
<div class="skill-content">
<div className="skill-card">
<i className="fa-solid fa-puzzle-piece"></i>
<h4 className="skill-title">Réflexion</h4>
<p className="skill-text">
Je trouve très stimulant le fait d'analyser un problème afin d'en trouver la solution
</p>
</div>
<div class="skill-card">
<i className="fa-solid fa-people-group"></i>
<h4 className="skill-title">Travail en équipe</h4>
<p className="skill-text">
Je suis à l'aise pour travailler en équipe ainsi que pour m'exprimer en public
</p>
</div>
<div className="skill-card">
<i className="fa-solid fa-user-ninja"></i>
<h4 className="skill-title">Capacité d'apatation</h4>
<p className="skill-text">
Je suis capable de m'adapter à tout type de situation ainsi que de gérer mon stress
</p>
</div>
<div className="skill-card">
<i className="fa-solid fa-lightbulb"></i>
<h4 className="skill-title">Curiosité</h4>
<p className="skill-text">
Curieux de nature, j'adore apprendre de nouvelles connaissances et compétences
</p>
</div>
</div>
<h3 className="skills">Tech</h3>
<div className="tech-container">
<div className="tech-card">
<div className="img-tech"></div>
<h4 className="tech-title">Html, CSS</h4>
<p className="tech-text">bla</p>
</div>
<div className="tech-card">
<div className="img-tech"></div>
<h4 className="tech-title">SASS</h4>
<p className="tech-text"></p>
</div>
<div className="tech-card">
<div className="img-tech"></div>
<h4 className="tech-title">Javascript</h4>
<p className="tech-text">bla</p>
</div>
<div className="tech-card">
<div className="img-tech"></div>
<h4 className="tech-title">React Js</h4>
<p className="tech-text">bla</p>
</div>
</div>
</div>
</div>
</div>
)
}
export default Resume
Depends on how you want to call your function inside yout JSX.
If you want to call your function every time your component renders you can just call it inside curly braces anywhere inside your JSX.
function myFunction() {
console.log('Hi, I rendered');
}
return (
<div>
{myFunction()}
</div>
)
If you want to call your function when an event happens, like a click event for example, you need to pass the function as a callback like so
function myOnClickFunction() {
console.log('I was clicked');
}
return (
<div>
<button onClick={myOnClickFunction}>Click me!</button>
</div>
)
Notice that I don't use the () when passing my function as a callback onClick={myOnClickFunction}, that is because I don't to run it now, I want to run it when the user clicks on it.
If you need to pass params inside your function you can write your callback as an arrow function and pass any params inside to it.
function myOnClickFunctionWithParams(name) {
console.log(`Hey ${name}, I was clicked`);
}
return (
<div>
<button onClick={() => myOnClickFunctionWithParams('John')}>Click me!</button>
</div>
)
In your case I think you will want to use onMouseEnter and onMouseLeave events on your div.
There are many default events you can use similar to onClick, you can fallback to this documentation anytime you have questions
React uses what's called a virtual-dom wich is built on top of the actual dom, and so they provide their own library of events methods, for your specific case, i would suggest you those react event methods:
onMouseEnter
and
onMouseLeave
learn more on how to handle mouse hover
You can use curly braces in your JSX to open a window to JavaScript, please refer the doc
First, a quick solution to the mouseover problem.
const Resume = () => {
const [hovered, setHovered] = useState(false);
return (
<div
onMouseOver={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
>
Text I want to show on mouse over
</div>
)
}
You'll see there's a lot less code than you're using, and no event listeners.. you're using what I like to call "psuedo React" - in many ways you're fighting against all of the reasons why React exists in first place!
There's a good video about this on YT: Stop Writing Fake React Code
My advice is to do some tutorials/courses on React and learn how to do the basics properly, it'll be time well spent!
On the "where to put my JS functions?" issue, in general, if the function depends upon any props or state from the component, then add it inside the component as a regular function.
If there are no dependents then the function is better off outside the component.. it's reusable, much easier to write unit tests for, and can't trigger any unexpected re-renders.
Related
I have card mapped with data from an "json" file and want the same details on the card to display on the modal menu
In the code snippet is the code for the cards that are displayed and the modal the modal works properly (opens and closes) but I now want to use the data from the cards in the modal but it doesn't show. I used the card key to specify which cards data to use but don't think that it works this way. I am new to react and think I need to use props but can't find any material that can explain it in a way I understand. Please help if you can any critsism will be gladly accepted and any other ways to improve my code will also help. Any learning material will also be hugely helpful.
Code:
{
details.map((details) => {
return (
<div className="card" key={details.id}>
<img src={details.image} alt="" />
<h5 className="board-name">{details.design}</h5>
<p className="board-size">Size: {details.size}</p>
<h6 className="board-price">{details.price}</h6>
<button className="add-to-cart" onClick={() =>
setModalDisplay(true)}> click me
</button>
</div>
)
})
}
{modalDisplay &&
<div className="backdrop">
<div className="cart-card" key={details.id}>
<div className="item-details">
<img src={details.image} alt="" width="98px" height="98px" />
<h4 className="item-name">{details.design}</h4>
<p className="item-size">{details.size}</p>
<h6 className="item-price">{details.price}</h6>
<button className="exit-modal" onClick={() =>
setModalDisplay(false)}>
</button>
</div>
<span className="modal-inputs">
<button className="minus-btn">-</button>
<input type="text" className="amount-input" value="01" />
<button className="plus-btn">+</button>
<button className="add-btn">Add to cart</button>
</span>
</div>
</div>
}
</div>
You could store the card data in an onClick that sets it in an state for example and use the state in the modal as props or directly. I think that would be the best option to use in this case.
I'm working with JavaScript & FrameWork7.
I am using the accordion element, and when I open the accordion I have to "identify" which item was opened, so I have on a variable the html element but I don't know how cand I get the "id" value
I'm using this to get the "element" open
app7.on('accordionOpen',function (el) {
console.log(el);
};
So, the console print this..
<li class="accordion-item">
<a class="item-content">
<div class="item-inner">
<div class="item-title" id="numero_jornada">Jornada 1</div>
</div>
</a>
<div class="accordion-item-content">
<div class="block" id="show-resul-jor-1">
</div>
</div>
</li>
How can I get the value for the Id="numero_jornada" ?
Could you help me, please?
try to use document.getElementByID("numero_jornada").value;
If your el is a normal HTMLElement, you can simply use el.id as its is in the HtmlElementNode Interface
works, thanks
let titulo = el.querySelector('.item-title');
// Mostrar ID del título
console.log(titulo.id); // numero_jornada
// Mostrar contenido del título
console.log(titulo.textContent); // Jornada #
A little help here, I'm stuck. I don't know even how to start.
I have this v-for for printing my "contracts".
I'm still not to submerged on vuejs workflow so I'm not being able to work around this.
How can I give a diferent background-color to every col div there? But not randomly, I want for them to keep the color even if the page is reloaded, my aproach was using the id of my contract and doing something with that but I don't understand much about vuejs to know how to do it.
Let's say I want to make a javascript function to give a class depending on the contractType.id, how do I execute that function with each loop? Is there a proper way to do this on vuejs?
<template>
<div class="row" v-if="contractTypes && contractTypes.length > 0">
<div class="col-md-4 c-button" v-for="(contractType, index) in contractTypes" :key="index" #click="choose($event.srcElement.innerHTML, index, contractType.id)">
<div class="col p-4 d-flex flex-column position-static text-center">
<strong class="d-inline-block mb-2 text-primary">World</strong>
<h3 class="mb-0">{{ translations && translations[contractType.id] ? translations[contractType.id].usecasetitle : contractType.usecasetitle }}</h3>
<p class="card-text mb-auto">{{ translations && translations[contractType.id] ? translations[contractType.id].description : contractType.title }}</p>
<button class="btn btn-primary">Click</button>
</div>
</div>
</div>
<div v-else>
<h1>Leider stehen für Sie derzeit keine Verträge zur Auswahl.</h1>
</div>
</template>
If you want custom styles on the different contract types, you can d a method:
/*
* #param {string} contract -- a foo bar
* #return {object} -- Bunch of boolean controlled classes
*/
getContractClasses (contract)
{
return {
'style1': contract === 'a string',
'style2': contract === 'another thing',
'style3': true, // This one is always going to be on and will have a bunch of shared styles between all of them
}
},
Then, in the template,
<h3 :class="getContractClasses(contract)">
Finally, just do the different styles in the style guide in the component housing the v-for.
Also, might I suggest an unwritten rule of sorts to remove all the logic from the template layer, and have that as a method or computed? Reading that long ternary inline is a big "No thank you", from me.
Does react have a clean way to get the this.props.values from a list item?
I basically want to get the current items props so I can populate a modal dialog with the data. as per below functions the custom props that I specify like 'id' are accessible, but I really would like to do something like this and have all the props
event.currentTarget.this.props.note
Handler
clicker(event){
console.log('clicking the clicker');
console.log(event.currentTarget.id);
this.setState({isEdit: true});
console.log(this.state.isEdit);
}
View
<div id={this.props.id} onClick={this.clicker} className="aui-item page-card off-track notecards">
<div className="project-details">
<div className="card-container">
<div className="left">
<h6>Title</h6>
<span>{this.props.note.content}</span>
<h6 className="compact">Last status report</h6>
<span>{this.props.note.updatedAt}</span>
</div>
<div className="right">
<span>something</span>
</div>
</div>
</div>
</div>
You can directly access props inside clicker
clicker(event){
console.log('clicking the clicker');
console.log(this.props.id);
this.setState({isEdit: true});
console.log(this.state.isEdit);
}
In this case it would be better to create separate component. In my opinion not necessary to create big huge views.
So, your component should be like this:
function Item({
id,
updatedAt,
content,
onClick,
}) {
// We should pass `id` variable to `onClick` handler.
return (
<div onClick={() => onClick(id)} className="aui-item page-card off-track notecards">
<div className="project-details">
<div className="card-container">
<div className="left">
<h6>Title</h6>
<span>{content}</span>
<h6 className="compact">Last status report</h6>
<span>{updatedAt}</span>
</div>
<div className="right">
<span>something</span>
</div>
</div>
</div>
</div>
);
}
Or, if you don't want to use separate component, you can access this.props variable from clicker event handler:
clicker(event){
// this.props are accesible here.
this.setState({isEdit: true});
}
I'm trying to use a jQuery UI progressbar that would show in a jQuery UI dialog when I click on an asp:Button.
The Button is declared as follow :
<asp:Button ID="Button2" runat="server" Text="Télécharger"
CausesValidation="False" onclick="Button2_Click" OnClientClick="javascript:displayDialog()"/>
The dialog is declared as follow :
<div id="dialog" title="Attente de téléchargement">
<p>Le fichier est en cours de préparation, le téléchargement devrait commencer sous peu.</p>
<div id="progressbar"></div>
</div>
And eventually the javascript :
<script type="text/javascript">
$(document).ready(function () {
$("#dialog").hide();
});
function displayDialog() {
$("#dialog").dialog();
$("#progressbar").progressbar({
value: false
});
$("#dialog").show();
}
</script>
This seems to work fine (since Both onclick and OnClientclick function are called). The code behind is executed correctly and the dialog shows too. However the animation of the progress bar doesnt work (see image below).
I don't understand what's going on. I've tried to not use show/hide but the property .css("display","none") and .css("display","block") of the $("#dialog") and the result is the same.
However If I don't hide the dialog on the $(document).ready the animation works fine. When I run this in the script tag:
$(document).ready(function () {
$("#dialog").dialog();
$("#progressbar").progressbar({
value: false
});
});
The dialog shows directly at the loading of the page like this :
which is correct (I obviously don't want it at the start but when you click on the button but still the progressbar shows correctly).
You are finding this issue because you have enclosed your progress bar within the dialog div
ERROR CODE:
<div id="dialog" title="Attente de téléchargement">
<p>Le fichier est en cours de préparation, le téléchargement devrait commencer sous peu.</p>
<div id="progressbar"></div>
</div>
Applying any changes to the Hidden elements would reflect.so better thing to do is to move the progress bar outside the dialog div.
CORRECTED CODE:
<div id="dialog" title="Attente de téléchargement">
<p>Le fichier est en cours de préparation, le téléchargement devrait commencer sous peu.</p>
</div>
<div id="progressbar"></div>
Happy Coding :)