1

I'm trying to assign a variable which will be a JSX element in ReactJS.

I want to do it like that:

const [useResultText, setResultText] = useState('');
const changeState = () => {
    const br = <br />
    setResultText('Hello' + br + 'world');
}

return (
    <div onClick={changeState}>{useResultText}</div>
);

Is there any way to do it?

2 Answers 2

1

This works fine, as JSX just represents certain kinds of JavaScript objects. But you have to define it properly:

const [useResultText, setResultText] = useState('');
const changeState = () => {
    const br = <br />
    setResultText(<React.Fragment>Hello{br}world</React.Fragment>);
}

return (
    <div onClick={changeState}>{useResultText}</div>
);

You might prefer something like a p or span tag over the fragment, depending on exactly what you want.

Sign up to request clarification or add additional context in comments.

Comments

0

You're almost there. Just set your state to an element:

import React from "react";
import "./styles.css";

export default function App() {
  const Elem = () => <div>Some stuff</div>;
  const [useResultText, setResultText] = React.useState(Elem);
  const changeState = () => {
    const br = <br />;
    setResultText(<div>Hello {br} World</div>);
  };

  return (
    <div className="App">
      <div onClick={changeState}>{useResultText}</div>
    </div>
  );
}

CS: https://codesandbox.io/s/vibrant-wind-0il8p?file=/src/App.js

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.