I'm trying to write a Tooltip component that appears on click on element. I've seen implementation of this kind of component where tooltip is kind of wrapped around another element, but that is not suitable for me.
I was thinking that maybe since I can access event.target I'll just select target's parent, then create new instance of a tooltip component with absolute positioning calculated from position of a target and append it to a parent, but I get an error that new instance of my Tooltip is not of node type and so it's not a valid child.
TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
Tooltip is a class component and it returns just a <div> with some text:
class Tooltip extends React.Component {
constructor(props) {
super(props);
}
basicStyle = {
width: 80,
height: 30,
backgroundColor: '#333333',
position: 'absolute',
left: this.props.tooltipLeft,
right: this.props.tooltipTop,
};
render() {
return <div style={this.basicStyle}>tooltip</div>;
}
}
And here's code for this demo app:
import React from 'react';
import Tooltip from './Tooltip';
import './App.css';
function App() {
const clickHandler = (event) => {
//get coordinates to position a Tooltip
const pos = event.target.getBoundingClientRect();
const tooltipLeft = pos.left + pos.width / 2;
const tooltipTop = pos.top - 20;
const tooltip = new Tooltip(tooltipLeft, tooltipTop);
const parent = event.target.parentNode;
parent.appendChild(tooltip);
};
return (
<div className='wrapper'>
<div className='box one' onClick={clickHandler}></div>
<div className='box two' onClick={clickHandler}></div>
<div className='box three' onClick={clickHandler}></div>
</div>
);
}
export default App;
I've also tried do the same thing with useRef and ReactDOM through use of portals (not sure if it's right way of using them), but it didn't help, even though error message no longer show up on click, just nothing happens.
In this case the code I used is following:
import React, { useRef } from 'react';
import ReactDOM from 'react-dom';
import Tooltip from './Tooltip';
import './App.css';
function App() {
const parentRef = useRef(null);
const clickHandler = (event) => {
//get coordinates to position a Tooltip
const pos = event.target.getBoundingClientRect();
const tooltipLeft = pos.left + pos.width / 2;
const tooltipTop = pos.top - 20;
const tooltip = new Tooltip(tooltipLeft, tooltipTop);
ReactDOM.createPortal(tooltip, parentRef.current);
};
return (
<div className='wrapper' ref={parentRef}>
<div className='box one' onClick={clickHandler}></div>
<div className='box two' onClick={clickHandler}></div>
<div className='box three' onClick={clickHandler}></div>
</div>
);
}
export default App;
I'm feeling like I'm missing something obvious here but I can't get it.
Can someone explain to me what I'm doing wrong in each of two attempts?
UPDATE:
I realized I should have said a bit more:
A little explanation of what I'm trying to achieve. Basicly I'm building a site with the ability to customize every element on it and that is the role of this tooltip component. I'm not using conditional rendering here because that would require me to manually add hooks/conditions to every possible place a Tooltip could be called or use just one instance of it with different possitions and content. I need to be able to show multiple Tooltips for a big number of elements and they should be able to be opened at the same time, this is why I went with class component and appendChild().
You should use the clickhandler to update your state, then conditionally draw the tooltip according to the state. I admit that I haven't used portals before so I'm not sure about that, but the "state" way is pretty straightforward.
Basically something like this:
const [pos,updatePos] = useState(null)
const clickHandler = (event) => {
updatePos(event.target.getBoundingClientRect())
}
return (
<div className='wrapper' ref={parentRef}>
<div className='box one' onClick={clickHandler}></div>
<div className='box two' onClick={clickHandler}></div>
<div className='box three' onClick={clickHandler}></div>
{ pos && (<ToolTip position={pos}/>) }
</div>
);
So it looks like you can't just stright up append react component using appendChild(), since appendChild() is a native javascript function and return value of react component(or in case of classes - of its render() method) is just object and not a node in any way (since react manages DOM for you). But I can't figure why portals don't work since I don't really know much about them.
If anybody interested, I also managed to write a custom hook/component that controls tooltips. I ended up using useState hook to store array all of the active tooltips and array of elements on which those tooltips was called. It's just a raw prototype, but it's working. I'll add some functionality and polish it a bit later, but for now it's just a tooltip dummy.
https://codepen.io/ClydeTheCloud/pen/MWKJQza
Related
How do I render before or after a child element in a container?
I am learning React by integrating it into my own website. I started with this:
function createErrorSection(name, title, description) {
const section = document.createElement('section');
const container = document.createElement('div');
const h2 = document.createElement('h2');
const p = document.createElement('p');
section.appendChild(container);
container.appendChild(h2);
container.appendChild(p);
section.id = name;
section.classList = 'section-error';
container.classList = 'section-error-container';
h2.textContent = title;
p.textContent = description;
return section;
}
Which I turned into this:
function createErrorSection(name, title, description) {
return (
<section id={name} className='section-error'>
<div className='section-error-container'>
<h2>{title}</h2>
<p>{description}</p>
</div>
</section>
);
}
This is eventually propagated down to either node.before(section) or node.after(section).
I checked inside ReactDOM, ReactDOM/server and React with no luck. I saw I could create an HTML string, but I need an HTMLElement and would rather not do my own rendering if it can be avoided (I want to learn the React way, I already know the vanilla way).
My end goal is to learn how and when to use React properly. I'd love to know the proper way, but insight, advice and workarounds are also greatly appreciated!
In React you rather want to create a custom component with a single argument which contains the corresponding properties:
// single argument contains all props
function ErrorSection({name, title, description}) {
return (
<section id={name} className='section-error'>
<div className='section-error-container'>
<h2>{title}</h2>
<p>{description}</p>
</div>
</section>
);
}
now you need to import ReactDOM and call render in order to show the component ErrorSecion with some specific property values inside a HTML node with the id #app. Make sure that your HTML document contains such a node.
import ReactDOM from "react-dom";
ReactDOM.render(
<ErrorSection name="..." title="..." description="..." />,
document.querySelector("#app")
);
Most of the react apps render some dynamically generated nested components into the DOM using a single empty HTML node inside the document body (e.g. div#app or div#root). So you most likely will only need to have a single ReactDOM.render call in your entire project.
First of all, component's name should be written in PascalCase.
In React, you should rethink the way you render elements.
There are different approaches for different purposes:
Pass components to the children prop
const Wrapper = ({ children }) => (
<div className="wrapper">
<h1>Wrapper heading</h1>
{children}
</div>
);
Now you can pass children to the wrapper this way:
const AnotherComponent = () => (
<Wrapper>
<div>Element that will be rendered where the children prop is placed</div>.
</Wrapper>
);
Pass components to custom props:
If you need to render many components in different spots, you can do this:
const MultiSpotComponent = ({ HeaderComponent, FooterComponent }) => (
<div>
{HeaderComponent}
<div>Some content</div>
{FooterComponent}
</div>
);
And then pass your components to the props the same way you do with attributes in HTML:
<MultiSpotComponent HeaderComponent={CustomHeader} FooterComponent={CustomFooter} />
Notice that I used self-closing tag for the component, because I don't render children inside it.
Render list
const AnotherComponent = () => {
const dynamicArray = ['some', 'dynamic', 'values'];
return (
<div>
{dynamicArray.map(value => <div key={value}>{value}</div>)}
</div>
);
};
I have described only 3 most-used approaches, but there are more ways to render elements. You can learn more at Official React Documentation
I'm attempting to do an animation with React and CSS classes. I have created a live demo, if you visit it and click the Start button you will see the text fade in and up one by one. This is the desired animation that I am after.
However, there seems to be issues of consistency when you hit Start multiple times and I cannot pinpoint why.
The Issue: Below is a recording of the issue, you can see the number 1 is not behaving as expected.
live demo
The process: Clicking Start will cancel any previous requestAnimationFrame' and will reset the state to it's initial form. It then calls the showSegments() function with a clean state that has no classNames attached to it.
This function then maps through the state adding a isActive to each segment in the state. We then render out the dom with a map and apply the new state.
This should create a smooth segmented animation as each class gets dropped one by one. However when i test this in Chrome (Version 56.0.2924.87 (64-bit)) and also on iOS, it is very inconsistent, sometimes it works perfectly, other times the first DOM element won't animate, it will just stay in up and visible it's completed transitioned state with "isActive".
I tried to replicate this issue in safari but it worked perfectly fine, I'm quite new to react so i am not sure if this is the best way to go about things, hopefully someone can offer some insight as to why this is behaving quite erratic!
/* MotionText.js */
import React, { Component } from 'react';
import shortid from 'shortid';
class MotionText extends Component {
constructor(props) {
super(props);
this.showSegments = this.showSegments.bind(this);
this.handleClickStart = this.handleClickStart.bind(this);
this.handleClickStop = this.handleClickStop.bind(this);
this.initialState = () => { return {
curIndex: 0,
textSegments: [
...'123456789123456789123456789123456789'
].map(segment => ({
segment,
id: shortid.generate(),
className: null
}))
}};
this.state = this.initialState();
}
handleClickStop() {
cancelAnimationFrame(this.rafId);
}
handleClickStart(){
cancelAnimationFrame(this.rafId);
this.setState(this.initialState(), () => {
this.rafId = requestAnimationFrame(this.showSegments);
});
}
showSegments() {
this.rafId = requestAnimationFrame(this.showSegments);
const newState = Object.assign({}, this.state);
newState.textSegments[this.state.curIndex].className = 'isActive';
this.setState(
{
...newState,
curIndex: this.state.curIndex + 1
},
() => {
if (this.state.curIndex >= this.state.textSegments.length) {
cancelAnimationFrame(this.rafId);
}
}
);
}
render(){
const innerTree = this.state.textSegments.map((obj, key) => (
<span key={obj.id} className={obj.className}>{obj.segment}</span>
));
return (
<div>
<button onClick={this.handleClickStart}>Start</button>
<button onClick={this.handleClickStop}>Stop</button>
<hr />
<div className="MotionText">{innerTree}..</div>
</div>
)
}
}
export default MotionText;
Thank you for your time, If there any questions please ask
WebpackBin Demo
Changing the method to something like this works
render(){
let d = new Date();
const innerTree = this.state.textSegments.map((obj, key) => (
<span key={d.getMilliseconds() + obj.id} className={obj.className}>{obj.segment}</span>
));
return (
<div>
<button onClick={this.handleClickStart}>Start</button>
<button onClick={this.handleClickStop}>Stop</button>
<hr />
<div className="MotionText">{innerTree}..</div>
</div>
)
}
How this helps is that, the key becomes different than previously assigned key to first span being rendered. Any way by which you can make the key different than previous will help you have this animation. Otherwise React will not render it again and hence you will never see this in animation.
I have a problem. So, I'm making react component and I need tooltip with button. Tooltip is working, but I can't place it where I want(I mean in the centre of the button and above that).
When I consoled log that, it's showing mne that e.target.offsetLeft and e.target.offsetTop are 0, but I gave it margin from both sides.
But actually when I place this code which have to place tooltip, then whole tooltip is not displayed:
tooltip.style.left = options.x + (options.w / 2) - (tooltip.offsetWidth / 2) + "px";
tooltip.style.top = (options.y - tooltip.offsetHeight - 10) + "px";
And it's my whole code:
import React from 'react';
import ReactDOM from 'react-dom';
import Style from 'style-it';
var Ink = require('react-ink');
import FontIcon from '../FontIcon/FontIcon';
var IconButton = React.createClass({
getInitialState() {
return {
iconStyle: "",
style: "",
cursorPos: {},
};
},
render() {
var _props = this.props,
...
globalTooltip = null,
...
function createTooltip(options) {
var tooltip = document.createElement("div");
tooltip.className = "tooltip";
tooltip.appendChild(document.createTextNode(_props.tooltip));
document.body.appendChild(tooltip);
tooltip.style.left = options.x + (options.w / 2) - (tooltip.offsetWidth / 2) + "px";
tooltip.style.top = (options.y - tooltip.offsetHeight - 10) + "px";
globalTooltip = tooltip;
console.log(options);
};
function showTooltip(e){
var options = {
w: e.target.offsetWidth,
x: e.target.offsetLeft,
y: e.target.offsetTop,
};
createTooltip(options);
};
function removeTooltip(e){
globalTooltip.parentNode.removeChild(globalTooltip);
};
return(
...
);
}});
ReactDOM.render(
<IconButton ... tooltip="aaaaa" />, document.getElementById('app')
);
And at this moment I can't even console log the options object :/
This is not a fix to the bug in your code, but I'm outlining some React principles and features that will help you solve your problems with just React (instead of mixing native DOM APIs and React APIs).
It is not advised to directly access the DOM elements using native DOM APIs when you are using React. Handling DOM is the job of React. That is what React is for. So if you modify/remove/insert elements from/into elements created using React, you are losing the whole advantage of that powerful library; minimal DOM change.
In simple words, if we modify the DOM elements created by React, and when React comes back and looks again to the DOM for performing its diffing algorithm, it is now something else, someone has altered it without React's knowledge; and React gets confused. Thus React fails do its optimization magics for what it is famous for.
To handle DOM nodes, React has a feature called Refs, which are essentially references to original DOM nodes. But you need to define it if you want to use it.
Example usage of ref:
class AutoFocusTextInput extends React.Component {
componentDidMount() {
this.textInput.focus();
}
render() {
return (
<input ref={(input) => { this.textInput = input; }} />
);
}
}
In the above example, if you want the offsetWidth, offsetHeight or any other DOM properties of <input> element, you can access it by this.textInput.offsetWidth, this.textInput.offsetHeight etc. But treat them as read-only.
If you want to alter the styles:
add a style attribute to the element in your JSX and modify the inline styles using React State and Lifecycle methods.
<input
style={{ left: this.state.offsetTop, top: this.state.offsetTop }}
ref={(input) => { this.textInput = input; }}
/>
I also saw in your code that you're using .removeChild and .appendChild in order to hide/show tooltip. Instead of that make use of React's Conditional Rendering.
example:
render() {
return (
<div>
{this.state.showToolTip ? <Tooltip ... /> : null}
{/* ... other stuff ... */}
</div>
);
}
If we are using React, then we should use it for a purpose, rather than just to say we are using it.
I'm displaying text that was stored in the database. The data is coming from firebase as a string (with newline breaks included). To make it display as HTML, I originally did the following:
<p className="term-definition"
dangerouslySetInnerHTML={{__html: (definition.definition) ? definition.definition.replace(/(?:\r\n|\r|\n)/g, '<br />') : ''}}></p>
This worked great. However there's one additional feature. Users can type [word] and that word will become linked. In order to accomplish this, I created the following function:
parseDefinitionText(text){
text = text.replace(/(?:\r\n|\r|\n)/g, '<br />');
text = text.replace(/\[([A-Za-z0-9'\-\s]+)\]/, function(match, word){
// Convert it to a permalink
return (<Link to={'/terms/' + this.permalink(word) + '/1'}>{word}</Link>);
}.bind(this));
return text;
},
I left out the this.permalink method as it's not relevant. As you can see, I'm attempting to return a <Link> component that was imported from react-router.However since it's raw HTML, dangerouslySetInnerHTML no longer works properly.
So I'm kind of stuck at this point. What can I do to both format the inner text and also create a link?
You could split the text into an array of Links + strings like so:
import {Link} from 'react-router';
const paragraphWithLinks = ({markdown}) => {
const linkRegex = /\[([\w\s-']+)\]/g;
const children = _.chain(
markdown.split(linkRegex) // get the text between links
).zip(
markdown.match(linkRegex).map( // get the links
word => <Link to={`/terms/${permalink(word)}/1`}>{word}</Link> // and convert them
)
).flatten().thru( // merge them
v => v.slice(0, -1) // remove the last element (undefined b/c arrays are different sizes)
).value();
return <p className='term-definition'>{children}</p>;
};
The best thing about this approach is removing the need to use dangerouslySetInnerHTML. Using it is generally an extremely bad idea as you're potentially creating an XSS vulnerability. That may enable hackers to, for example, steal login credentials from your users.
In most cases you do not need to use dangerouslySetHTML. The obvious exception is for integration w/ a 3rd party library, which should still be considered carefully.
I ran into a similar situation, however the accepted solution wasn't a viable option for me.
I got this working with react-dom in a fairly crude way. I set the component up to listen for click events and if the click had the class of react-router-link. When this happened, if the item has a data-url property set it uses browserHistory.push. I'm currently using an isomorphic app, and these click events don't make sense for the server generation, so I only set these events conditionally.
Here's the code I used:
import React from 'react';
import _ from 'lodash';
import { browserHistory } from 'react-router'
export default class PostBody extends React.Component {
componentDidMount() {
if(! global.__SERVER__) {
this.listener = this.handleClick.bind(this);
window.addEventListener('click', this.listener);
}
}
componentDidUnmount() {
if(! global.__SERVER__) {
window.removeEventListener("scroll", this.listener);
}
}
handleClick(e) {
if(_.includes(e.target.classList, "react-router-link")) {
window.removeEventListener("click", this.listener);
browserHistory.push(e.target.getAttribute("data-url"));
}
}
render() {
function createMarkup(html) { return {__html: html}; };
return (
<div className="col-xs-10 col-xs-offset-1 col-md-6 col-md-offset-3 col-lg-8 col-lg-offset-2 post-body">
<div dangerouslySetInnerHTML={createMarkup(this.props.postBody)} />
</div>
);
}
}
Hope this helps out!
Background
I am trying to learn how to use the React Shallow Rendering TestUtil and had the tests passing until I added an onClick event handler to both; It seems that there must be some difference with the Accordion.toggle function I am trying to use in Accordion.test.js vs this.toggle in Accordian.js...but I can't figure it out.
Question
How can I get the two highlighted tests in Accordian.test.js to pass?
Steps to reproduce
Clone https://github.com/trevordmiller/shallow-rendering-testing-playground
npm install
npm run dev - see that component is working when you click "Lorem Ipsum"
npm run test:watch - see that tests are failing
There are a number of issues preventing your tests from passing.
Looking at the test "should be inactive by default":
Accordion.toggle in your test is a property of the Accordion class, and this.toggle in your code is a property of a instance of the Accordion class - so in this case you are comparing two different things. To access the 'instance' method in your test you could replace Accordion.toggle with Accordion.prototype.toggle. Which would work if it were not for this.toggle = this.toggle.bind(this); in your constructor. Which leads us to the second point.
When you call .bind() on a function it creates a new function at runtime - so you can't compare it to the original Accordion.prototype.toggle. The only way to work around this is to pull the "bound" function out of the result from render:
let toggle = result.props.children[0].props.onClick;
assert.deepEqual(result.props.children, [
<a onClick={toggle}>This is a summary</a>,
<p style={{display: 'none'}}>This is some details</p>
]);
As for your second failing test "should become active when clicked":
You try calling result.props.onClick() which does not exist. You meant to call result.props.children[0].props.onClick();
There is a bug in React that requires a global "document" variable to be declared when calling setState with shallow rendering - how to work around this in every circumstance is beyond the scope of this question, but a quick work around to get your tests passing is to add global.document = {}; right before you call the onClick method. In other words where your original test had:
result.props.onClick();
Should now say:
global.document = {};
result.props.children[0].props.onClick();
See the section "Fixing Broken setState()" on this page and this react issue.
Marcin Grzywaczewski wrote a great article with a workaround for testing a click handler that works with shallow rendering.
Given a nested element with an onClick prop and a handler with context bound to the component:
render() {
return (
<div>
<a className="link" href="#" onClick={this.handleClick}>
{this.state.linkText}
</a>
<div>extra child to make props.children an array</div>
</div>
);
}
handleClick(e) {
e.preventDefault();
this.setState({ linkText: 'clicked' });
}
You can manually invoke the function value of the onClick prop, stubbing in the event object:
it('updates link text on click', () => {
let tree, link, linkText;
const renderer = TestUtils.createRenderer();
renderer.render(<MyComponent />);
tree = renderer.getRenderOutput();
link = tree.props.children[0];
linkText = link.props.children;
// initial state set in constructor
expect(linkText).to.equal('Click Me');
// manually invoke onClick handler via props
link.props.onClick({ preventDefault: () => {} });
tree = renderer.getRenderOutput();
link = tree.props.children[0];
linkText = link.props.children;
expect(linkText).to.equal('Clicked');
});
For testing user events like onClick you would have to use TestUtils.Simulate.click. Sadly:
Right now it is not possible to use ReactTestUtils.Simulate with Shallow rendering and i think the issue to follow should be: https://github.com/facebook/react/issues/1445
I have successfully tested my click in my stateless component. Here is how:
My component:
import './ButtonIcon.scss';
import React from 'react';
import classnames from 'classnames';
const ButtonIcon = props => {
const {icon, onClick, color, text, showText} = props,
buttonIconContainerClass = classnames('button-icon-container', {
active: showText
});
return (
<div
className={buttonIconContainerClass}
onClick={onClick}
style={{borderColor: color}}>
<div className={`icon-container ${icon}`}></div>
<div
className="text-container"
style={{display: showText ? '' : 'none'}}>{text}</div>
</div>
);
}
ButtonIcon.propTypes = {
icon: React.PropTypes.string.isRequired,
onClick: React.PropTypes.func.isRequired,
color: React.PropTypes.string,
text: React.PropTypes.string,
showText: React.PropTypes.bool
}
export default ButtonIcon;
My test:
it('should call onClick prop when clicked', () => {
const iconMock = 'test',
clickSpy = jasmine.createSpy(),
wrapper = ReactTestUtils.renderIntoDocument(<div><ButtonIcon icon={iconMock} onClick={clickSpy} /></div>);
const component = findDOMNode(wrapper).children[0];
ReactTestUtils.Simulate.click(component);
expect(clickSpy).toHaveBeenCalled();
expect(component).toBeDefined();
});
The important thing is to wrap the component:
<div><ButtonIcon icon={iconMock} onClick={clickSpy} /></div>
Hope it help!