Target dom element of react component without ref - javascript

I installed a react-component called react-geosuggest in my project. I need to find the <label> dom element in the <Geosuggest> component and insert an onClick handler to <label>. Is there a way to target the <label> tag without altering the <Geosuggest> component's code.
Here's the JSX
render() {
return (
<div>
<Geosuggest
id = "searchbar"
label = " "
placeholder = ""
initialValue = {this.state.location}
onChange = {this.onInputChange}
onSuggestSelect = {this.onSelection}
onClick = {this.toggleSearch}
className = {this.state.expand}
inputClassName = {this.state.expand}
// Name a calling reference
ref = 'geosuggest_component'
/>
</div>
);
}
Here's the HTML output
<div class="geosuggest">
<div class="geosuggest__input-wrapper">
<label for="searchbar"></label>
<input class="geosuggest__input" type="text" id="searchbar">
</div>
</div>

You have to use vanillajs. In your component, you can access geosuggest_component ref in componentDidMount:
componentDidMount() {
// findDOMNode returns an HTMLElement
const node = ReactDOM.findDOMNode(this.refs.geosuggest_component);
// Then search the label
const label = node.querySelector('label');
// Now, you can do anything you want with label
label.addEventListener('click', () => console.log('clicked'))
}
I use ReactDOM.findDOMNode because in this case, this.refs.geosuggest_component returns a React component.
The method findDOMNode will give you the HTMLElement you need.
However, a better way to declare a ref is by using a callback:
ref={node => this.geosuggest_component = node}
Now in componentDidMount:
const node = ReactDOM.findDOMNode(this.geosuggest_component);

Related

can't append h1 element to parent div in React?

i'm creating a simple react website that's supposed to do some calculations and find out Joules of my input values after the calculations...right now the input values are already preset but i will remove the value="" from my <input> later.
here is the .JSX component file that's the issue...one of the components.
import React, { Component } from 'react';
import Atom_icon from './cartridges.png';
class Joule_calc extends Component {
render(){
return (
<div className='Joule_div'>
<h3 style={{color:"white", textAlign:"center"}}>JOULE CALCULATOR</h3>
<label className='lab1'>WEIGHT=/GRAMS</label><br></br>
<input className='weight_inp' type='text' value="2" />
<label className='lab2'>SPEED=M/S</label><br></br>
<input className='speed_inp' type='text' value="5" />
<button className='count_button' onClick={this.Create_response}>CALCULATE</button>
<h1 className='Result_joule'></h1>
</div>
)
}
Create_response(){
console.log("creating response...")
let sum = document.createElement("h1")
sum.className = 'Result_joule'
sum.textContent = "678"
let div_panel = document.getElementsByClassName("Joule_div")
div_panel.append('Result_joule')
}
Returned_values(){
let weight_val = document.getElementsByClassName("weight_inp")[0].value;
let speed_val = document.getElementsByClassName("speed_inp")[0].value;
let final_calculation = weight_val * speed_val
return final_calculation
}
}
export default Joule_calc
so when i run my code i get
Uncaught TypeError: div_panel.append is not a function
at Create_response (Joule_calc_window.jsx:31:1)
i don't get why i can't append my new element to the div. it says it's not a function so what's the solution then? i'm new to React and web so probably it's just a noobie thing.
also i tried directly creating a h1 inside the 'Joule_div' like this.
<h1 className='Result_joule'>{"((try returning here from one of these methods))"}</h1>
but that of course failed as well. So would appreciate some help to get what's going on. i'm trying to add a number after the button click that's in h1 and in future going to be a returned number after calculating together the input values in a method.i imagine that something like
MyMethod(){
value = values calculated
return value
}
and later grab it with this.MyMethod
example
<h1>{this.MyMethod}</h1>
this is a example that of course didn't work otherwise i wouldn't be here but at least gives you a clue on what i'm trying to do.
Thank you.
You don't leverage the full power of react. You can write UI with only js world thanks to JSX. State changes triggering UI update.
I may miss some specificaiton, but fundamental code goes like the below. You should start with function component.
// Function component
const Joule_calc = () =>{
// React hooks, useState
const [weight, setWeight] = useState(0)
const [speed, setSpeed] = useState(0)
const [result,setResult] = useState(0)
const handleCalculate = () =>{
setResult(weight*speed)
}
return (
<div className="Joule_div">
<h3 style={{ color: 'white', textAlign: 'center' }}>JOULE CALCULATOR</h3>
<label className="lab1">WEIGHT=/GRAMS</label>
<br></br>
<input className="weight_inp" type="text" value={weight} onChange={(e)=>setWeight(parseFloat(e.target.value))} />
<label className="lab2">SPEED=M/S</label>
<br></br>
<input className="speed_inp" type="text" value={speed} onChange={(e)=>setSpeed(parseFloat(e.target.value))} />
<button className="count_button" onClick={handleCalculate}>
CALCULATE
</button>
<h1 className='Result_joule'>{result}</h1>
</div>
)
}
export default Joule_calc;
div_panel is an collection of array which contains the classname ["Joule_div"]. so first access that value by using indexing . and you should append a node only and your node is "sum" not 'Result_joule' and you should not use textcontent attribute because you will be gonna definitely change the value of your result as user's input value
Create_response(){
console.log("creating response...")
let sum = document.createElement("h1")
sum.className = 'Result_joule'
//sum.textContent = "678"
let div_panel = document.getElementsByClassName("Joule_div")
div_panel[0].append('sum')
}
if any problem persists , comment below

How to use useEffect inside a handler or vice versa?

I have a function which is handler of onChange and get value of input
and also I have a function for search in an array using searched value coming from that input
and render a component that contains searched array as props.
But I have a problem
when I search it works but after second letter and when the input is empty it shows the last search.
I think it should be handled with useEffect but I dont how to solve or may be I am wrong
I need help to correct that
thanks for your help.
these are my code :
getting search value part and sending as argument :
function BasePage({handleClick, handleSearch }) {
const [searchValue, setSearchValue] = useState('');
useEffect(() => {
function handleChangeSearchInput(e) {
const newSearchValue = e.target.value;
setSearchValue(newSearchValue);
handleSearch(searchValue);
}
})
return (
<div>
<fieldset>
<legend>Search</legend>
<input
value = {searchValue}
onChange = {handleChangeSearchInput}
placeholder = "Enter name to search"
type = "text"
/>
<button onClick={() => handleClick('add-record-form')}>Add</button>
</fieldset>
<br />
{searchValue.length > 0 && <SearchRecord record = {searchValue} />}
</div>
);
}
and this filters in parent component :
function handleSearch(searchValue) {
const searchedTerm = contacts.filter(contact => (contact.name.toLowerCase().includes(searchValue.toLowerCase())));
setSearchTerms(searchedTerm);
}
and I use map to show them .
You shouldn't need useEffect for this. Just have the handler deal with both the setting of state, and the updating.
function handleChangeSearchInput(e) {
const newSearchValue = e.target.value;
setSearchValue(newSearchValue);
handleSearch(newSearchValue);
}

How to manipulate child's render output

I'm using a component form a third party library and I want to manipulate the render output.
Let's say we have two components:
// third party component that I don't have access to its code
const ThirdPartyComponent = () => (
<div>
<span>
...
</span>
</div>
)
// My component using the third party component
const MyComponent = () => (
<div className="wrapper">
<ThirdPartyComponent />
</div>
)
Normally the output will be:
<div class="wrapper">
<div>
<span>
...
</span>
</div>
</div>
Now I want to manipulate the third party component such that my component renders this:
<div class="wrapper">
<span>
...
</span>
</div>
Or in other words unwrap the rendered content from an unwanted <div /> element.
1. I can't change the third party code
2. The child component doesn't forward ref
Any idea how to do this? 🤔
If:
the third party component is a function component, and
the third party component does not use refs (or if you're careful), and
you don't mind losing the component boundary for ThirdPartyComponent (essentially MyComponent will "be" ThirdPartyComponent), and
you solemnly swear you understand this might break in the future
you can call the component as if it was a function, then dig into the returned JSX object and get the first child, á la:
const ThirdPartyComponent = () => (
<div style={{border: "1px solid orange"}}>
<span>...</span>
</div>
);
const MyComponent = () => {
const thirdPartyDiv = ThirdPartyComponent(); // This is naughty!
const span = thirdPartyDiv.props.children; // The child is the span
return (
<div className="wrapper">
{span}
</div>
);
}
Alternately, if all you're doing is re-wrap the component, you could modify thirdPartyDiv.props.className to suit your needs...
const MyComponent = () => {
const thirdPartyDiv = ThirdPartyComponent(); // This is naughty!
thirdPartyDiv.props.className = "wrapper";
return thirdPartyDiv;
}

Appending a new dom element in react

I've created a custom component and I want to add child element when the component renders if a certain property is set to be true. I used the following code, but the component is not rendered. what am I doing wrong here.
let deleteNode = '';
if(deletable){
deleteNode = '<div />'
}
let defaultClasses = 'chips chips-rounded';
return (
<div className={classNames(classes, defaultClasses)} onClick={ this.onClick }>
{avatar}
<span>{this.props.labelText}</span>
{deleteNode}
</div>
)
You are trying to render a component but actually you are just sending string in your deleteNode. Your code should be something like below
if(deletable){
deleteNode = (<div />);
}
I different approach would be:
render() {
const defaultClasses = 'chips chips-rounded'
return (
<div className={classNames(classes, defaultClasses)} onClick={ this.onClick }>
{avatar}
<span>{this.props.labelText}</span>
{deletable && <div />}
</div>
)
}
So you don't need the extra if checking.

creating elements in React

I don't understand how elements are created in React.
I have some code below where the goal is to create elements on a form submit using a value from a refs - so for every submit in a form, it creates a new <h1> tag with the content of the textbox inside of it. A sample of what I'm trying to do looks like:
...
addHeader(e) {
e.preventDefault();
const newHeader = this.refs.post.value;
var newpost = React.createElement("h1", {
type: "text",
value: newHeader
});
}
...
render() {
return (
<div className="form-section">
{ newPost }
<form onSubmit={this.addHeader.bind(this)}>
<input id="input-post" type="text" placeholder="Post Here" ref="post" />
<input type="submit" value="Submit" />
</form>
<button className="form-section__submit" onClick={this.clearFields.bind(this)}>Clear All</button>
</div>
);
}
Basically my thinking is in my addHeader() function I'm assigning a variable of newPost to the method and calling it within my component. This code is causing 2 errors:
33:9 warning 'newpost' is assigned a value but never used no-unused-vars
49:13 error 'newPost' is not defined no-undef
What I don't understand, is (from what I can see) I am assigning a value to that variable and also using it in the component that I am rendering... along with that, I don't understand this error message. How can something be assigned a value but be undefined at the same time...? Is it because it's in the wrong scope? How do I declare where the new element is rendered specifically in the component?
I read the documentation but it doesn't give a clear answer as to how to control where in the component the new element is rendered.
Made some changes to your code. You're going to want to initialize component state in your constructor. In your addHeader method you will use this.setState to update the state of the component with a new posts value including the value of this.input. I changed your ref on the input an actual ref. You take the element and store on this. Every time you add a new post you will get a new <h1> with the value of the textarea.
...
addHeader(e) {
e.preventDefault();
this.setState((prevState, props) => {
return { posts: [ ...prevState.posts, this.input.value ] };
});
}
...
render() {
const { posts } = this.state;
return (
<div className="form-section">
{ posts.map( text => <h1>{ text }</h1> ) }
<form onSubmit={this.addHeader.bind(this)}>
<input id="input-post" type="text" placeholder="Post Here" ref={ el => this.input = ref } />
<input type="submit" value="Submit" />
</form>
<button className="form-section__submit" onClick={this.clearFields.bind(this)}>Clear All</button>
</div>
);
}
As an aside: Binding functions in the render method of react components will cause a performance hit. There is no need to re-bind the this context of the function on every render. this.clearFields.bind(this) should become this.clearFields and you will need to add this.clearFields = this.clearFields.bind(this) to your constructor. You do not need to bind functions that are not used as callbacks.
You're going to want to do the same thing for this.addHeader.bind(this).

Categories

Resources